I was trying to get the Grove Ultrasonic Ranger to work with CircuitPython on the Xiao, but I believe that it’s simply too slow to handle the timing. I tried looking into this with very simple code:
while True:
led.value = True
led.value = False
The resulting pulse hi/low times are 26.4 us, and I don’t see how to get the Ultrasonic Ranger to work with that sort of timing resolution. For reference the trigger pulse is typically 10 us. I even attempted with pulseio, but couldn’t get it to work.
Please let me know if anyone finds a way. Maybe it would need to be a native library written in C?
Maybe you can try ArduPy, which has almost the same performance as using C.
Any idea if the decorators mentioned in this article could help Embedded Python: Cranking Performance Knob up to Eleven!? Edited to add - these don’t appear to be enabled for this board.
Hi Keith, we do have a library for similar device here: https://github.com/adafruit/Adafruit_CircuitPython_HCSR04/blob/master/adafruit_hcsr04.py
What did you try with pulseio
? Did you try PulseIn.resume
with a trigger duration? https://circuitpython.readthedocs.io/en/latest/autoapi/pulseio/index.html#pulseio.PulseIn.resume That is what we use for DHT11 temp sensors which require a trigger pulse.
Ok - I actually had looked at that library and believe that the initial timeout check in the hcsr04 library is what led me astray. It could be added back, but as a quick proof of concept this minimal code does work:
import board
import pulseio
import time
sig = pulseio.PulseIn(board.D7)
sig.pause()
sig.clear()
sig.resume(10)
time.sleep(1) # should poll len(sig) here with a timeout
sig.pause()
print("len(sig) = ", len(sig))
if len(sig) != 0:
print("sig[0] = ", sig[0])
print("Distance = {} [cm]".format(sig[0]*0.017))
I’m not sure why that library doesn’t pass a pulse length to resume, and manually toggles the trigger instead?
Anyways I think that this should work as long as pulseio is used.
Without pulseio there are a couple of potential issues. One is speed and being able to toggle pins quickly enough, and make quality measurements. The other issue is time.monotonic() and long run-times. I believe that even with a faster CPU the library would likely fail after a day or so of runtime do to the time being represented by a single precision float. A workaround would be for the higher level application to reset the timebase, but I don’t believe there’s a way to do that.
Here’s my attempt at porting the HC-SR04 library:
CircuitPython library for the Grove ultrasonic range sensor
It seems to work o.k. on the Seeeduino Xiao.