I am just starting to work with the pico.
I have not been able to get the Ultrasonic Ranger working with the pico. Here is the code I am working with.
I never see “Goodbye” in my output.
_TIMEOUT1 = 1000
_TIMEOUT2 = 10000
def button3_handler():
print('Hello')
pin = machine.Pin(1, machine.Pin.OUT)
pin.value(0)
time.sleep_us(2)
pin.value(1)
time.sleep_us(10)
pin.value(0)
pin.init(machine.Pin.IN)
t0 = time.time()
count = 0
while count < _TIMEOUT1:
if pin.value:
print('Broke1')
break
count += 1
print( "Count1: {}".format( count ))
if count >= _TIMEOUT1:
print('None1')
return
t1 = time.time()
count = 0
while count < _TIMEOUT2:
if not pin.value:
print('Broke2')
break
count += 1
print( "Count2: {}".format( count ))
if count >= _TIMEOUT2:
print('None2')
return
print('Goodbye')
Are you using the Grove Unit?
are you using this unit?
or you could use
Yes, I am using the Grove - Ultrasonic Distance Sensor
sorry i dont understand raspberry pi programming but i found this on the wiki
import sys
import time
from grove.gpio import GPIO
usleep = lambda x: time.sleep(x / 1000000.0)
_TIMEOUT1 = 1000
_TIMEOUT2 = 10000
class GroveUltrasonicRanger(object):
def __init__(self, pin):
self.dio =GPIO(pin)
def _get_distance(self):
self.dio.dir(GPIO.OUT)
self.dio.write(0)
usleep(2)
self.dio.write(1)
usleep(10)
self.dio.write(0)
self.dio.dir(GPIO.IN)
t0 = time.time()
count = 0
while count < _TIMEOUT1:
if self.dio.read():
break
count += 1
if count >= _TIMEOUT1:
return None
t1 = time.time()
count = 0
while count < _TIMEOUT2:
if not self.dio.read():
break
count += 1
if count >= _TIMEOUT2:
return None
t2 = time.time()
dt = int((t1 - t0) * 1000000)
if dt > 530:
return None
distance = ((t2 - t1) * 1000000 / 29 / 2) # cm
return distance
def get_distance(self):
while True:
dist = self._get_distance()
if dist:
return dist
Grove = GroveUltrasonicRanger
def main():
if len(sys.argv) < 2:
print('Usage: {} pin_number'.format(sys.argv[0]))
sys.exit(1)
sonar = GroveUltrasonicRanger(int(sys.argv[1]))
print('Detecting distance...')
while True:
print('{} cm'.format(sonar.get_distance()))
time.sleep(1)
if __name__ == '__main__':
main()
It does not appear that GitHub - Seeed-Studio/grove.py: Python library for Seeedstudio Grove devices will run on the Raspberry Pi Pico.
I have also posted an issue on that repository.
I now have working MicroPython code for the grove_ultrasonic_ranger.py
Where is the best place to publish it ?
The code applies to the Raspberry Pi 4B, so it can be applied to the Pi Pico as well.
Here is the microPython library for any one else that wants to use the Ultrasonic Ranger on a RP2040 board:
1 Like
nice job! thanks for posting that … i may actually try it on my setup