Ultrasonic HC-SR04P Using Raspberry Pi Pico

Ultrasonic with Maker Pi Pico

Introduction

This time we will program an ultrasonic sensor with Maker Pi Pico using MicroPython. An ultrasonic sensor is used to measure the distance of a target object by emitting ultrasonic sound waves. It then converts the reflected sound into an electrical signal. The ultrasonic frequency is higher than the audible sound frequency.

Video

Watch this video to know more about it.

Hardware Preparation

This is the list of items used in the video.

Software Preparation

  1. Thonny Python IDE for Beginners

from machine import Pin, PWM
import utime
Trig = Pin(27, Pin.OUT)
Echo = Pin(26, Pin.IN, Pin.PULL_DOWN)
Buzzer = PWM(Pin(18))
def CheckDistance():
SpeedOfSoundInCM = 0.034
Trig.low()
utime.sleep_us(2)
Trig.high()
utime.sleep_us(10)
Trig.low()
exitLoop = False
loopcount = 0 #used as a failsafe if the signal doesn't return
while Echo.value() == 0 and exitLoop == False:
loopcount = loopcount + 1
delaytime = utime.ticks_us()
if loopcount > 3000 : exitLoop == True
while Echo.value() == 1 and exitLoop == False:
loopcount = loopcount + 1
receivetime = utime.ticks_us()
if loopcount > 3000 : exitLoop == True
if exitLoop == True: #We failed somewhere
return 0
else:
distance = ((receivetime delaytime) * SpeedOfSoundInCM) / 2
return distance
while True:
distance = CheckDistance()
print(distance)
if CheckDistance() < 10:
Buzzer.duty_u16(3000)
Buzzer.freq(1700)
utime.sleep(0.05)
Buzzer.duty_u16(0)
utime.sleep(CheckDistance() / 1000)

References

  1. Connecting a Ultrasonic Sensor to the @Raspberry Pi Pico

Thanks for reading this tutorial. If you have any technical inquiries, please post at Cytron Technical Forum.

Please be reminded, this tutorial is prepared for you to try and learn.
You are encouraged to improve the code for better application.

1 thought on “Ultrasonic HC-SR04P Using Raspberry Pi Pico”

Leave a Comment

Your email address will not be published.

Share this Tutorial

Share on facebook
Share on whatsapp
Share on email
Share on print
Share on twitter
Share on pinterest
Share on facebook
Share on whatsapp
Share on email
Share on print
Share on twitter
Share on pinterest

Latest Tutorial

Real-Time IoT Room Monitoring on Maker Pi Pico Using pyRTOS
Build an IoT Plant Monitoring System with MicroBit and Grove WiFi Module
Snap & Fit ABS Case and ICE Tower Cooling Fan Case Stress Test
Raspberry Pi Zero 2 W – Quad-core and 64-bit CPU
IoT Push Notification Using Rain Sensor with MicroBit
Tutorials of Cytron Technologies Scroll to Top