In this video lesson we explore creating a portable distance measurement widget using the Raspberry Pi Pico W, the HC-SR04 Ultrasonic Sensor, and the SSD1306 OLED display.
The schematic we use for this project is as follows:
In this work, we use the State Machines on the Pi Pico to ensure precise timing. Below, we include the code developed in the lesson above:
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 |
import rp2 from machine import Pin,I2C #*************** import time from ssd1306 import SSD1306_I2C #************** i2c2=I2C(1,sda=Pin(2), scl=Pin(3), freq=400000) dsp=SSD1306_I2C(128,64,i2c2) @rp2.asm_pio(set_init=rp2.PIO.OUT_LOW) def pulse_program(): wrap_target() pull(block) mov(x,osr) set(pins,1)[31-1] set(pins,0) wait(1,pin,0) label("land") in_(pins,1) # 1 Cycle mov(y,isr) # 1 Cycle jmp(not_y,"moveOn") # 1 Cycle jmp(x_dec,"land") # 1 Cycle label("moveOn") mov(isr,invert(x)) push() wrap() triggerPin = Pin(18,Pin.OUT) echoPin = Pin(19, Pin.IN) sm=rp2.StateMachine(0,pulse_program, freq=1000000, set_base=triggerPin,in_base=echoPin) sm.active(1) while True: sm.put(0xFFFFFFFF) print("Pulse Launched") clockCycles=(sm.get())*4/2 distance=clockCycles*.0342 print("Distance to Target: ",distance) dsp.text("Distance: "+str(distance),0,16) dsp.show() dsp.fill(0) time.sleep(.25) |