Project Overview: Visualizing Proximity
Visual feedback is one of the most intuitive ways to interact with sensor data. This project, RGB LED Based on Distance, serves as a foundational tutorial for beginners to bridge the gap between physical sensors and visual actuators. By utilizing an ultrasonic sensor to measure distance, the Arduino changes the color of an RGB LED setup (using individual Red, Green, and Blue LEDs) to indicate how close an object is.
Whether you're building a parking sensor for a garage or a simple experimental setup, this project teaches critical concepts in timing, signal processing, and conditional logic.
Materials & Components
- Arduino Uno R3: The main microcontroller platform.
- HC-SR04 Ultrasonic Sensor: A popular "sonar" sensor that uses high-frequency sound pulses to detect objects.
- 3x 5mm LEDs (Red, Green, Blue): To represent different distance zones.
- 3x 220-ohm Resistors: Vital for current limiting to protect the LEDs from burnout.
- Breadboard & Jumper Wires: For easy, solderless circuit prototyping.
Engineering Deep Dive: The Physics of Sound
The HC-SR04 operates on a simple but refined principle of physics. It sends out a sonic burst (Ping) and then waits for the echo to bounce back from an object.
- The Trigger: The Arduino sends a 10-microsecond pulse to the
trigPin. - The Pulse: The sensor converts this into an eight-cycle sonic burst at 40 kHz.
- The Echo: The sound travels at 340 m/s (approx. 0.034 cm/µs). When the pulse hits an object and returns, the
echoPingoes HIGH for a duration proportional to the distance. - The Calculation: Distance = (Time × Speed of Sound) / 2. We divide by 2 because the sound traveled to the object and back.

Code Logic Analysis
The provided code is structured neatly into functional blocks:
- Custom Color Functions: Instead of repeating
analogWritecommands in the loop, the author created helper functions likeRed(),Green(), andBlue(). This makes the main loop much easier to read and debug. - Clamping Mechanism: The
clamp()function is a critical addition. It prevents the system from processing "noise" or unrealistic distance values (e.g., negative numbers or distances beyond 50cm where the sensor loses accuracy). - Threshold Zoning:
- Near (1 - 15 cm): Blue LED lights up, indicating very close proximity.
- Mid (16 - 32 cm): Green LED lights up, indicating a safe middle distance.
- Far (33 - 50 cm): Red LED lights up, indicating the object is further away but within the monitored range.
Wiring & Setup
The hardware setup is straightforward. The LEDs are connected to PWM-capable pins (3, 4, 5) to allow for brightness control via analogWrite(). The ultrasonic sensor uses pins 8 (trigger) and 9 (echo).

Conclusion
This project is an excellent entry point into the world of "Sensing and Control." By mastering the HC-SR04 sensor and basic LED actuation, you can move on to more complex projects like autonomous robots, smart home security systems, or advanced user interfaces.