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.

Bodgers – Servos

This week we will connect a SG90 mini servo to our Pico.

Wire the breadboard as shown below:

First test that the buttons are working correctly with the following code.

from machine import Pin
from time import sleep

button_1 = Pin(18, Pin.IN, Pin.PULL_UP)
button_2 = Pin(19, Pin.IN, Pin.PULL_UP)

while True:
    if button_1.value() == 0:
        print("Button 1 is Pressed")
    if button_2.value() == 0:
        print("Button 2 is Pressed")
    sleep(0.1)

Next here is the code for the Servo.

from machine import Pin, PWM
from time import sleep

servo_pin = PWM(Pin(0))
servo_pin.freq(50)

def servo(degrees):
    if degrees > 180:
        degrees = 180
    if degrees < 0:
        degrees = 0
       
    max_duty = 8050
    min_duty = 1650
       
    new_duty = (min_duty + (max_duty - min_duty) * (degrees/180))
    servo_pin.duty_u16(int(new_duty))

servo(0)
sleep(0.5)
servo(90)
sleep(0.3)
servo(180)
sleep(0.3)

This weeks challenge is to combine both pieces of code above so that when button 1 is pressed the servo arm will move one way and when button 2 is pressed it will move in the opposite direction.