Aim. To switch an LED ON when an object is closer than a set distance and OFF when it is farther away.
Components. Arduino UNO R3, HC-SR04, 1 LED, 220 Ω resistor, breadboard, jumper wires.
Concepts used. Combining a sensor input, a decision (if), and an output; thresholds; hysteresis.
Wiring. Use the same wiring as Practical 4 (Trig on pin 9, Echo on pin 10) and add the LED circuit from Practical 1 on pin 8.
| Part | Arduino |
|---|---|
| HC-SR04 VCC / GND | 5V / GND |
| HC-SR04 Trig | Pin 9 |
| HC-SR04 Echo | Pin 10 |
| LED (through 220 Ω) | Pin 8, cathode to GND |
Program.
const int trigPin = 9;
const int echoPin = 10;
const int ledPin = 8;
const float threshold = 20.0; // centimetres
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
float getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH, 30000);
if (duration == 0) return -1; // no echo
return duration * 0.0343 / 2.0;
}
void loop() {
float distance = getDistance();
Serial.println(distance);
if (distance > 0 && distance < threshold) {
digitalWrite(ledPin, HIGH); // object near: LED ON
} else {
digitalWrite(ledPin, LOW); // far or no echo: LED OFF
}
delay(100);
}How it works. The function getDistance() wraps the measurement steps from Practical 4 so the main loop stays short. The if statement compares the distance to the threshold. The condition distance > 0 ignores the invalid reading (−1).
Expected result. Moving a hand closer than 20 cm turns the LED on; moving away turns it off.
Extensions.
- Hysteresis. To stop flicker around the threshold, switch ON below 18 cm and OFF above 22 cm.
- Parking sensor. Add a buzzer and make the beep interval depend on distance (closer means faster).
- Three zones. Green LED above 50 cm, yellow from 20 to 50 cm, red below 20 cm.
- Brightness by distance. Use
analogWrite()withmap()so the LED gets brighter as the object approaches.
// Extension 4 example (LED on PWM pin 9 means Trig must move, e.g. to pin 7)
int brightness = constrain(map((int)distance, 5, 50, 255, 0), 0, 255);
analogWrite(ledPin, brightness);Viva questions
- What is a threshold?
- Why do we check
distance > 0? - How is this similar to a combinational logic circuit?
Show viva answers
- A fixed value used to decide between two actions.
- Because −1 means no echo was received and should not turn the LED on.
- The output depends only on the present input, with no memory. The hysteresis extension, which remembers the last state, makes it sequential.