deckle studioOpen in the editor

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.

NetPins
GNDA1 GNDD1 KD2 KD3 KD4 KD5 KU2 GND
5VA1 5VU2 VCC
ECHOA1 ~D11/MOSIU2 ECHO
L1A1 ~D3R1 1
L1_AD1 AR1 2
L2A1 D4R2 1
L2_AD2 AR2 2
L3A1 ~D5R3 1
L3_AD3 AR3 2
L4A1 ~D6R4 1
L4_AD4 AR4 2
L5A1 D7R5 1
L5_AD5 AR5 2
TRIGA1 D12/MISOU2 TRIG
D1
LED
D2
LED
D3
LED
D4
LED
D5
LED

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

More examples: Arduino