Interfacing Ultrasonic Sensor Using Raspberry Pi Pico

by Manodeep in Circuits > Raspberry Pi

7499 Views, 4 Favorites, 0 Comments

Interfacing Ultrasonic Sensor Using Raspberry Pi Pico

IMG_5284.jpg

An ultrasonic sensor is an electronic device that measures the distance of a target object by emitting ultrasonic sound waves and converts the reflected sound into an electrical signal. Ultrasonic waves travel faster than the speed of audible sound (i.e. the sound that humans can hear). Ultrasonic sensors have two main components: the transmitter (which emits the sound using piezoelectric crystals) and the receiver (which encounters the sound after it has traveled to and from the target).

In order to calculate the distance between the sensor and the object, the sensor measures the time it takes between the emission of the sound by the transmitter to its contact with the receiver. The formula for this calculation is D = ½ T x C (where D is the distance, T is the time, and C is the speed of sound ~ 343 meters/second). For example, if a scientist set up an ultrasonic sensor aimed at a box and it took 0.025 seconds for the sound to bounce back, the distance between the ultrasonic sensor and the box would be:

D = 0.5 x 0.025 x 343or about 4.2875 meters.

Supplies

1. HC - SR04 Ultrasonic Sensor module

2. Raspberry Pi Pico

Connect the Ultrasonic Sensor Module With Raspberry Pi According to the Schematics.

HCSR04.png

NB:- If you have a 5v HC-SR04 module like me, please connect it through a LOGIC LEVEL SHIFTER, otherwise the code will not work properly.

Write the Code, Save It As HCSR04.py and Run It.

from machine import Pin
import utime
trigger = Pin(14, Pin.OUT)
echo = Pin(15, Pin.IN)
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)

Downloads

Output

2021-06-02 (8).png