from machine import Pin, I2C, time_pulse_us
from time import sleep_us, sleep
import ssd1306
import machine
i2c_dev = I2C(0, scl=Pin(5), sda=Pin(4), freq=200000)
display = ssd1306.SSD1306_I2C(128, 64, i2c_dev)
display.text('Hello, World!', 0, 0, 1)
button = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP)
display.show()
ECHO_PIN = 22
TRIGGER_PIN = 26
trigger = Pin(TRIGGER_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
CM = True
def detect_dist():
global pulse_duration
trigger.low()
sleep_us(2)
trigger.high()
sleep_us(10)
trigger.low()
pulse_duration = time_pulse_us(echo, 1, 30000)
if CM:
pulse_duration = pulse_duration / 58
else:
pulse_duration = pulse_duration / 148
while True:
detect_dist()
display.fill(0)
display.text("Distance: ", 0, 0, 1)
display.text(str(pulse_duration) + (" CM" if CM else " INCH"), 0, 20, 1)
sleep(0.1)
display.show()
if not button.value():
CM = not CM