⭐⭐⭐ Challenge
⏱️ 25 minutes
Distance meter with light bar
You make a light bar that shows how close something is. Far away: no lights. The closer it is, the more lights turn on. First green, then orange, and very close is red.
🧰 What do you need?
🗺️ Wiring diagram
Follow the wires from the Arduino to each part. You can choose the wire colors yourself.
| From | To |
|---|---|
Arduino UNO · D9 |
Distance sensor HC-SR04 · Trig |
Arduino UNO · D10 |
Distance sensor HC-SR04 · Echo |
Arduino UNO · 5V |
Distance sensor HC-SR04 · Vcc |
Arduino UNO · GND |
Distance sensor HC-SR04 · Gnd |
Arduino UNO · D6 |
RGB LED ring (8 LEDs) · DI |
Arduino UNO · 5V |
RGB LED ring (8 LEDs) · 5V |
Arduino UNO · GND |
RGB LED ring (8 LEDs) · GND |
🛠️ This is how you build it
- Connect the HC-SR04: Trig to pin 9, Echo to pin 10, Vcc to 5V, and Gnd to GND.
- Connect the LED-ring: DI to pin 6, 5V to 5V, and GND to GND.
💻 The code
// Distance meter with light bar
// The closer you get, the more lights turn on: green, then orange, then red.
#include <Adafruit_NeoPixel.h>
const int TRIG_PIN = 9; // Trig of the HC-SR04 on pin 9
const int ECHO_PIN = 10; // Echo of the HC-SR04 on pin 10
const int RING_PIN = 6; // DI of the LED ring on pin 6
const int NUM_LEDS = 8;
const int MAX_DISTANCE = 80; // Farther than this (in cm): all lights off
Adafruit_NeoPixel ring(NUM_LEDS, RING_PIN, NEO_GRB + NEO_KHZ800);
long measureDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long time = pulseIn(ECHO_PIN, HIGH, 30000);
if (time == 0) return 999;
return time / 58;
}
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
ring.begin();
ring.setBrightness(40);
ring.show();
}
void loop() {
long distance = measureDistance();
Serial.print(F("Distance: "));
Serial.print(distance);
Serial.println(F(" cm"));
// How many lights should turn on? Close = 8, far away = 0
int count = map(constrain(distance, 0, MAX_DISTANCE), 0, MAX_DISTANCE, NUM_LEDS, 0);
for (int i = 0; i < NUM_LEDS; i++) {
if (i < count) {
if (i < 3) ring.setPixelColor(i, ring.Color(0, 255, 0)); // Green
else if (i < 6) ring.setPixelColor(i, ring.Color(255, 120, 0)); // Orange
else ring.setPixelColor(i, ring.Color(255, 0, 0)); // Red
} else {
ring.setPixelColor(i, 0); // Off
}
}
ring.show();
delay(100);
}
🧠 What does the code do?
measureDistance()measures the distance with the HC-SR04.map()changes the distance into a number of lights: 0 to 8.- The first 3 lights are green, the next 3 orange, and the last 2 red.
🎯 Try this…
- Make all lights blink red when you are closer than 10 cm
- Add the buzzer that beeps at red
- Make the meter more sensitive: all lights on at 40 cm instead of 80 cm
🚀 Build this project with Codey: open codey.online/starter-kits/uno/projects/distance-light-bar and click MAKE THIS. Then the code and the wiring diagram are ready right away.
Codey Online is a product of OTRONIC