Interrupt Driven HC-SR04 MicroPython Pi Pico
by stevensarns in Circuits > Raspberry Pi
10 Views, 0 Favorites, 0 Comments
Interrupt Driven HC-SR04 MicroPython Pi Pico

All of the SR04 drivers I found were written with "wait" loops, meaning that the driver would hang (block) until the wait condition was satisfied. In the case of the SR04 Ultrasonic distance sensor this would be up to 2.5 milliseconds. This driver is interrupt driven, consequently does not interfere with normal operation of the microcontroller.
Supplies
Pi Pico
SR04 Ultrasonic distance sensor
Programming
Programming is straightforward. I used Thonny. There are many versions of the SR04 but I think this will work with any of them. The only issue might be the timeout of an ECHO pulse that does not detect a reflection. In my case it was 150 milliseconds. The decision to run the sensor at 5 Hz (trig_rate = Timer(mode=Timer.PERIODIC, period=200, callback=sr04trigger)) is to ensure that a trigger pulse is not applied until the echo signal has reset. I tested several sensors and found that the longest ECHO pulse ranged from 70 mS to 180 mS. On the other hand, perhaps it would not affect the sensor to apply the TRIG pulse during a sampling period. If that is the case, the trigger rate could be increased without concern and the code would return the last valid result. I tested this at a trigger rate of 100 triggers/second and the results appeared ok although I did detect a few bogus returns.