This week I used both an analog and a digital sensor to control two LEDs in different ways. I used the ultrasonic distance sensor to measure distance. For the digital sensor. My setup controls two LEDs: one blinks and the other changes brightness using PWM.
Here’s how it works:
LED1, connected to a regular digital pin, blinks faster when an object is closer and slower when it’s farther away. The delay between blinks is based on the distance in centimeters. So the closer the object, the faster the LED blinks. If the object is far, the LED blinks slowly.
LED2, connected to a PWM pin, changes brightness based on the same distance. But instead of getting dimmer when the object is far (which is more common), I made it do the opposite—it’s dim when the object is close and bright when it’s far away. I know it’s the reverse of what people usually do, but I wanted to try something different and see how it looked in action.
the code :
// Pin definitions const int trigPin = 7; // HC-SR04 trigger pin const int echoPin = 6; // HC-SR04 echo pin const int led1Pin = 2; // LED1 pin (digital) const int led2Pin = 3; // LED2 pin (PWM) // Variables const int maxDistance = 255; // Maximum meaningful distance (cm) int distance = 0; // Measured distance in centimeters int brightness = 0; // Variable for brightness void setup() { Serial.begin(9600); pinMode(led1Pin, OUTPUT); pinMode(led2Pin, OUTPUT); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } long getUltrasonicDistance() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); return pulseIn(echoPin, HIGH); } void loop() { // Measure distance distance = 0.01723 * getUltrasonicDistance(); // Cap the distance reading if(distance > maxDistance) distance = maxDistance; if(distance < 2) distance = 2; // HC-SR04 minimum range // Serial output Serial.print(distance); Serial.println(" cm"); // LED1: Blink with distance-dependent delay (capped) digitalWrite(led1Pin, HIGH); delay(distance); digitalWrite(led1Pin, LOW); delay(distance); // LED2: Brighter when closer, dimmer when farther //brightness = map(distance, 2, maxDistance, 255, 0); // Inverted mapping //brightness = constrain(brightness, 0, 255); // Ensure valid PWM //Serial.println(brightness); brightness = distance; analogWrite(led2Pin, brightness);
video:
https://drive.google.com/drive/u/0/folders/1Kk2lkQgoAyybXSYWVmY2Dog9uQVX_DMq
future improvement:
In the future, I’d like to add sound that reacts to distance, like pitch changes as you move closer or farther. I also want to make the project more interactive overall—maybe by adding more sensors or letting users trigger different responses through movement or touch. This would make the experience feel more playful and alive.
schematic: