3.2. Distance Fade LED

This example uses the HC-SR04 ultrasonic distance sensor to measure distance from an object, based on that measured value we will control the brightness of an LED.
At the end of this example you will learn:
- How to use Ultrasonic distance sensor
- How to map values from one range to another
Parts required:
- Soldered NULA Mini Board
- Breadboard
- 1 x LED (any color)
- 1 x 330 Ohm resistor
- HC-SR04 Ultrasonic distance sensor
- 1 x Qwiic cable
- Some jumper wires

Putting the components together
- To connect an LED, connect the longer (positive) leg to the pin 5 via jumper wire, and shorter (negative) leg to GND via 330 Ohm resistor.
- Connecting the Ultrasonic sensor is pretty simple and straightforward, just plug in one end of Qwiic cable in the NULA Mini board, and the other end in the sensor itself.
- If you are not using the Qwiic connector, follow the table below for connections:
| NULA Mini | HC-SR04 |
|---|---|
| VCC | 5V |
| TRIG | IO4 |
| ECHO | IO3 |
| GND | GND |

Code Example
Import UltrasonicSensor driver module and other necessary built in modules.
from UltrasonicSensor import UltrasonicSensor
from machine import I2C, Pin, PWM
import time
Create an ultrasonic sensor object that communicates via I2C (Qwiic mode).
# Create I2C an 'UltrasonicSensor' object which initializes the sensor in Qwiic mode with default I2C pins
#i2c = I2C(0, scl=Pin(7), sda=Pin(6))
#sensor = UltrasonicSensor(i2c)
# Native
sensor = UltrasonicSensor(trig_pin=4, echo_pin=3)
Assign LED to pin 5 and enable PWM output on that pin. Set frequency to 5000 Hz (blink rate).
led = Pin(5)
led_pwm = PWM(led)
led_pwm.freq(5000)
Function to convert a value from one range to another. In this case, the measured distance from sensor will be converted into PWM duty cycle value for controling LED brightness.
def map_distance_value(value, in_min, in_max, out_min, out_max):
if value < in_min:
value = in_min
elif value > in_max:
value = in_max
return int((value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
Main loop which triggers a new distance measurement and reads the distance in cenimeters. Small delay is added to ensure stable reading. If object is too far, then set it to 400 cm max. After getting distance value we then pass it to map_distance_value function where distance (0-400 cm) is converted to PWM duty cycle (4095-0). Closer objects = brighter LED. In the end add small delay to so echoes from last ping 'die out'.
while True:
sensor.takeMeasure()
time.sleep(0.1)
distance = sensor.getDistance()
if distance > 400:
distance = 400
pwm_value = map_distance_value(distance, 0, 400, 65535, 0)
led_pwm.duty_u16(pwm_value)
time.sleep(0.25)