- Code: Select all | TOGGLE FULL SIZE
import board
import digitalio
from time import sleep, monotonic, monotonic_ns
trigger = digitalio.DigitalInOut(board.GP2)
trigger.direction = digitalio.Direction.OUTPUT
echo = digitalio.DigitalInOut(board.GP3)
echo.direction = digitalio.Direction.INPUT
while True:
trigger.value = True
sleep(0.00001)
trigger.value = False
while not echo.value:
pass
start_time = monotonic_ns()
while echo.value:
pass
end_time = monotonic_ns()
print ("Distancia")
print (((end_time - start_time)/1000)/58)
sleep(0.2)
(I know there's a library that can be used with this sensor but it also gives me the incorrect readings, and besides it mainly uses this same method for the readings.)
The code I posted gives me a distance of 0 when really close to the sensor. Then distance changes to 16.8373 from about 5cm to about 20cm. After that I get 33,6746, and after that around 50....
Not being an expert at using CIrcuitpython I tried the same with Micropython, using the following code:
- Code: Select all | TOGGLE FULL SIZE
from machine import Pin
from time import sleep, ticks_us
trigger = Pin(2, Pin.OUT)
echo = Pin(3, Pin.IN)
print ("Start")
while True:
trigger.value(True)
sleep(0.00001)
trigger.value(False)
while not echo.value():
pass
start_time = ticks_us()
while echo.value():
pass
end_time = ticks_us()
print ("Distancia")
print ((end_time - start_time)/58)
sleep(0.2)
This code gives me reasonably accurate readings. So, is there anything wrong in my Circuitpython code that I'm not seeing? Or is this a problem with the Pico port of CP? Any ideas will be appreciated.
Thanks!