Bodgers – More Distance Sensors

This week we are going to try making a measuring device using our HC-SR04 sensors.

First we’ll wire our circuit up.

Next let’s test our circuit with the following code.

from machine import Pin
import utime
from time import sleep

trigger = Pin(17, Pin.OUT)
echo = Pin(16, Pin.IN, Pin.PULL_DOWN)
buzzer = Pin(15, Pin.OUT)


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")
    return distance


def buzz():
    buzzer.value(1)
    sleep(0.5)
    buzzer.value(0)
    sleep(0.5)


while True:
    dist = ultra()
    if dist < 30:
        buzz()
    utime.sleep(1)

This week’s challenge is to rewrite the code so the the closer to something the sensor is the faster it will beep.

Once we have that done we will look at transferring the code onto the Pico itself and running it from a battery.

Leave a comment