Distance-Sensing Light
The closer you get, the brighter the LED glows.
What you’ll learn
- Ultrasonic distance with HC-SR04: bounce a ping, time the echo.
- PWM via analogWrite — fake-analog brightness from a digital pin.
- Mapping one range of values onto another with map().
What you need
| Item✓ | Qty | ~Cost | Where to buy | |
|---|---|---|---|---|
| Arduino Uno (or Nano clone) | Arduino Uno (or Nano clone) | 1 | GHS 120.00 | Online — official Uno is ~GHS 375; a Nano clone is ~GHS 75. |
| USB cable for the board | USB cable for the board | 1 | GHS 15.00 | Probably already in the kit. |
| HC-SR04 ultrasonic sensor | HC-SR04 ultrasonic sensor | 1 | GHS 30.00 | Online. |
| Red 5 mm LED | Red 5 mm LED | 1 | GHS 1.50 | Online. |
| 220 Ω resistor | 220 Ω resistor | 1 | GHS 0.75 | Online. |
| Half-size breadboard + jumpers | Half-size breadboard + jumpers | 1 | GHS 30.00 | Online. |
| TotalTotal | ~GHS 197.25 | |||
Build it step by step
Wire the HC-SR04
VCC → 5V, GND → −rail, TRIG → D9, ECHO → D10.
Wire the LED on a PWM pin
D6 → 220 Ω → LED anode → LED cathode → −rail. D6 supports analogWrite.
Upload the code
Open the Arduino IDE, paste the code, hit Upload.
Wave your hand near the sensor
Close = bright. Far = dim. Beyond ~50 cm the LED is fully off.
How it works
pulseIn(ECHO, HIGH) waits for the echo pin to go high then measures how long it stays high — in microseconds. Sound travels ~343 m/s, so distance = (time_us / 2) / 29 in centimetres. We map that into a brightness value 0-255 and feed it to analogWrite, which uses PWM to fake an analog voltage on the LED.
If something’s not working
LED is always full bright
- · ECHO wire is loose — the timer never gets a real reading.
Distance reading jumps around
- · Sensor is angled — they need a flat reflecting surface.
- · Soft objects (clothes, hair) absorb the ping. Use a book or your palm.
Try this next
Print the distance to the Serial Monitor for debugging.
Replace the LED with a buzzer that beeps faster as you get closer — like a real parking sensor.
The code
Paste this into the Arduino IDE and hit Upload. Each line tells the board what to do, in order — the more lines you read, the more you understand.
// Distance-sensing light
const int TRIG = 9;
const int ECHO = 10;
const int LED = 6;
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(LED, OUTPUT);
}
void loop() {
digitalWrite(TRIG, LOW); delay(2);
digitalWrite(TRIG, HIGH); delay(10);
digitalWrite(TRIG, LOW);
long us = pulseIn(ECHO, HIGH);
long cm = us / 58; // ~58us per cm round-trip
int b = map(cm, 5, 50, 255, 0);
if (b < 0) b = 0;
if (b > 255) b = 255;
analogWrite(LED, b);
delay(50);
}