This week we will be using the HC-SR04 Ultrasonic Distance Sensor

Wire up the sensor as shown below

Here is the code we will need for the sensor.
#From www.tomshardware.com/how-to/raspberry-pi-pico-ultrasonic-sensor
from machine import Pin
import utime
trigger = Pin(17, Pin.OUT)
echo = Pin(16, Pin.IN, Pin.PULL_DOWN)
def ultra():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
distance = (timepassed * 0.0343) / 2
print("The distance from object is ",distance,"cm")
while True:
ultra()
utime.sleep(1)
Once this is working you can move on to this week’s challenge. Combine this with the LED code from the last session so that the LED flashes when the distance measured by the sensor is less than 30CM. Here is the LED code:
from machine import Pin
from time import sleep
led = Pin(15, Pin.OUT)
def flash():
led.value(1)
sleep(0.5)
led.value(0)
sleep(0.5)
while True:
flash()