I have an old HC-Sr04 ultrasonic sensor. I don’t know if it’s GPIO voltage compatible with the 3.3V microcontroller.
On the internet, I found that the old sensors work with 5V.
So, I used a voltage divider made of 1K ohm and 1.5K ohm Surface mount resistors. To bring down the 5V to a suitable 3V.
I want to reduce the voltage level on the ECHO pin of the ultrasonic sensor to a safe level for the Raspberry Pi Pico’s GPIO pins. Let’s assume we have chosen resistors R1 and R2 with values of 1K and 1.5K, respectively.
You can also use the voltage divider calculator for this
Voltage Divider Calculator
Using the voltage divider formula, we can calculate the output voltage at the midpoint (E_3) of the voltage divider circuit:
V_out = V_in * (R2 / (R1 + R2))
Since the Vsys pin of the Raspberry Pi Pico provides a voltage of 5V, we can calculate the output voltage:
V_out = 5V * (1.5K / (1K + 1.5K))
= 5V * (1.5K / 2.5K)
= 5V * 0.6
= 3V
With the given resistor values, the output voltage at the midpoint of the voltage divider circuit will be 3V. This 3V output is within the safe voltage range for the GPIO pins of the Raspberry Pi Pico.
Code Implementation:
To implement the interface between the ultrasonic sensor and the Raspberry Pi Pico, we will utilize MicroPython, a lightweight Python implementation for microcontrollers. The following code snippet demonstrates the necessary steps:
from machine import Pin
import utime
trigger = Pin(2, Pin.OUT)
echo = Pin(3, Pin.IN)
def ultra():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(10)
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)
Leave a Reply