from machine import Pin, SoftI2C, I2C
import time
import ssd1306
# Initialize I2C for OLED Display
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# Initialize Motion Sensor
motion_sensor = Pin(14, Pin.IN)
# Initialize Ultrasonic Sensor
trig = Pin(4, Pin.OUT)
echo = Pin(5, Pin.IN)
# Initialize LED
led1 = Pin(2, Pin.OUT)
led2 = Pin(25,Pin.OUT)
led3 = Pin(26,Pin.OUT)
def show_display(message, distance):
oled.fill(0)
oled.text(message, 10, 10)
oled.text("Distance: {:.2f} cm".format(distance), 10, 30)
oled.show()
while True:
# Check for motion
if motion_sensor.value():
oled.fill(0)
oled.text("Motion Detected", 10, 10)
oled.show()
led1.on()
else:
oled.fill(0)
oled.text("No Motion", 10, 10)
oled.show()
led1.off()
# Measure distance with Ultrasonic Sensor
trig.on()
time.sleep_us(10)
trig.off()
while echo.value() == 0:
pulse_start = time.ticks_us()
while echo.value() == 1:
pulse_end = time.ticks_us()
pulse_duration = pulse_end - pulse_start
distance = (pulse_duration * 34300) / 2 # Speed of sound = 343 m/s
distance = distance/10**6
if distance > 300: # Adjust this threshold as needed
show_display("APTX", distance)
led3.on()
led2.off()
elif distance > 200:
show_display("APTX4869", distance)
led2.on()
#led3.off()
else:
show_display("SHIHO", distance)
led1.on()
time.sleep(1)