Arduino Uno: ultrasonic distance on an LED bar
HC-SR04 measures, five LEDs show how close.
- Arduino Uno
- HC-SR04
Open in the simulatorNo account needed: press Simulate and it runs.
How it works
The HC-SR04 (TRIG D12, ECHO D11) measures the distance with pulseIn(). Five LEDs on D3–D7 form a bar: the closer the object, the more LEDs light (below 100, 70, 45, 25 and 10 cm). Change the distance of U2 in the inspector while the simulation runs; the serial console shows the value in cm.
Wiring
Each line is one connection (net) and the pins it joins.
| Net | Pins |
|---|---|
| GND | A1 GNDD1 KD2 KD3 KD4 KD5 KU2 GND |
| 5V | A1 5VU2 VCC |
| ECHO | A1 ~D11/MOSIU2 ECHO |
| L1 | A1 ~D3R1 1 |
| L1_A | D1 AR1 2 |
| L2 | A1 D4R2 1 |
| L2_A | D2 AR2 2 |
| L3 | A1 ~D5R3 1 |
| L3_A | D3 AR3 2 |
| L4 | A1 ~D6R4 1 |
| L4_A | D4 AR4 2 |
| L5 | A1 D7R5 1 |
| L5_A | D5 AR5 2 |
| TRIG | A1 D12/MISOU2 TRIG |
Parts
Firmware
sketch.ino · 22 lines
// HC-SR04 (TRIG D12, ECHO D11) measures the distance; the LED bar on D3..D7 shows how close:
// more LEDs = closer (green, green, yellow, yellow, red)
const int TRIG = 12, ECHO = 11;
const int LEDS[] = { 3, 4, 5, 6, 7 };
const int STEPS[] = { 100, 70, 45, 25, 10 }; // cm: LED k lights below STEPS[k]
void setup() {
Serial.begin(115200);
pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT);
for (int k = 0; k < 5; k++) pinMode(LEDS[k], OUTPUT);
}
void loop() {
digitalWrite(TRIG, LOW); delayMicroseconds(2);
digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW);
unsigned long us = pulseIn(ECHO, HIGH, 30000); // 30 ms: about 5 m
float cm = us / 58.0;
for (int k = 0; k < 5; k++) digitalWrite(LEDS[k], us > 0 && cm < STEPS[k]);
Serial.print(F("Distance: "));
if (us == 0) Serial.println(F("out of range")); else { Serial.print(cm, 1); Serial.println(F(" cm")); }
delay(60); // let the echo die out
}Open in the simulator