from machine import Pin, I2C
import time
import ssd1306
i2c = I2C(0, scl=Pin(1), sda=Pin(0))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
pir = Pin(15, Pin.IN)
trig = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
clk = Pin(16, Pin.IN)
dt = Pin(17, Pin.IN)
last_clk = clk.value()
position = 0
state = 0
last_pir = 0
def get_distance():
trig.low()
time.sleep_us(2)
trig.high()
time.sleep_us(10)
trig.low()
while echo.value() == 0:
start = time.ticks_us()
while echo.value() == 1:
end = time.ticks_us()
duration = time.ticks_diff(end, start)
return (duration * 0.0343) / 2
def read_encoder():
global last_clk, position
current_clk = clk.value()
if current_clk != last_clk:
if dt.value() != current_clk:
position += 1
else:
position -= 1
last_clk = current_clk
while True:
oled.fill(0)
current = pir.value()
if current == 1 and last_pir == 0:
state = not state
last_pir = current
distance = get_distance()
if state == 1 and distance < 100:
oled.text("WARNING!", 0, 0)
oled.text("Object <100cm", 0, 20)
elif distance > 100:
read_encoder()
oled.text("Safe Distance", 0, 0)
oled.text("Dist: {:.1f}cm".format(distance), 0, 20)
oled.text("Move: {}".format(position), 0, 40)
else:
oled.text("No Motion", 0, 0)
oled.show()
time.sleep(0.2)