In this video lesson we will show you how to get precise distance measurements with the HC-SR04 Ultrasonic sensor. We show how measurement stability and accuracy can be improved by using the Raspberry Pi Pico PIO State Machines to trigger and monitor the sensor. For your convenience, the code is presented below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# ==================================================================== # DISCLAIMER: # This code is provided as-is for educational and experimental # purposes only. The author makes no representations or warranties of # any kind concerning the safety, suitability, or accuracy of this # code. Use at your own risk. The author assumes no liability for any # damages, system failures, security breaches, or network issues # resulting from the use or implementation of this script. # ==================================================================== import rp2 from machine import Pin import time @rp2.asm_pio(set_init=rp2.PIO.OUT_LOW) def pulse_program(): wrap_target() pull(block) mov(x,osr) set(pins,1)[10-1] set(pins,0) wait(1,pin,0) label("land") mov(y,pins) # 1 clock cycle jmp(not_y,"moveOn") #1 clock cycle jmp(x_dec,"land") # 1 clock cycle label("moveOn") mov(isr,invert(x)) push() wrap() triggerPin = Pin(16,Pin.OUT) echoPin = Pin(17, Pin.IN) sm=rp2.StateMachine(0,pulse_program, freq=1000000, set_base=triggerPin,in_base=echoPin) sm.active(1) ts=.25 while True: sm.put(0xFFFFFFFF) print("Pulse Launched") clockCycles=sm.get()*3/2 distance=clockCycles*.0342 print("Distance to Target: ",distance) time.sleep(ts) |
