Raspberry Pi Pico Ultrasonic Sensor:
Raspberry Pi Pico Ultrasonic Sensor Interfacing and programming- In this article, I am going to use the most popular HC-SR04 Ultrasonic Sensor with the Raspberry Pi Pico. You know ultrasonic sensor is one of the most commonly used sensors and is usually used for obstacle detection in robotics, it is also used for monitoring the water level, and so on. For now, I will make a simple distance meter and you will be able to see the measured distance on the Oled display module. So, let’s go ahead and take a look at the circuit diagram.
Other Tools and Components:
*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!
Ultrasonic Sensor Interfacing with Raspberry Pi Pico:
The SSD1306 Oled display module connections with the Raspberry Pi Pico remains exactly the same. The VCC pin is connected with the VBus which is Pin40 of the Raspberry Pi Pico. Trigger pin is connected with GP3, Echo pin connected with GP2, and the GND pin of the ultrasonic sensor is connected with the GND pin of the Raspberry Pi Pico board.
Ultrasonic Sensor Raspberry Pi Pico Programming:
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
from oled import Write, GFX, SSD1306_I2C
from oled.fonts import ubuntu_mono_15, ubuntu_mono_20
trigger = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
WIDTH = 128
HEIGHT = 64
i2c = I2C(0, scl=Pin(17), sda=Pin(16), freq=200000)
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)
measured_time = distance()
distance_cm = (measured_time * 0.0343) / 2
write20 = Write(oled, ubuntu_mono_20)
write20.text("Distance: ", 0, 0)
The Oled display code remains exactly the same, this time I defined the trigger and echo pins which are connected with GP3 and GP2. I defined the trigger pin as the output and the echo pin as the input.
The actual code is placed inside the distance() function which measure the time duration of the signal as it travels from the transmitter to the receiver. Finally, the measured time is converted into centimeters and then divided by 2 to get the actual distance. While these other lines of code simply display the text and measured distance on the Oled display module. Now, let’s go ahead and run this code.
I just built myself a distance meter, now I can use this for obstacle detection, for controlling an electronic Door lock, for measuring the water level inside a tank, for controlling lights, and so on.