from machine import Pin, I2C
import time
# PIR Sensor
pir = Pin(2, Pin.IN)
# Ultrasonic Sensor
trig = Pin(3, Pin.OUT)
echo = Pin(4, Pin.IN)
# LEDs
red = Pin(10, Pin.OUT)
yellow = Pin(11, Pin.OUT)
green = Pin(12, Pin.OUT)
# LCD (I2C)
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400000)
# Simple LCD function (basic)
def lcd_write(msg):
print(msg) # Wokwi will show in serial monitor if LCD lib not added
# Measure distance
def get_distance():
trig.low()
time.sleep_us(2)
trig.high()
time.sleep_us(10)
trig.low()
while echo.value() == 0:
pass
start = time.ticks_us()
while echo.value() == 1:
pass
end = time.ticks_us()
duration = time.ticks_diff(end, start)
distance = (duration * 0.034) / 2
return distance
motion_count = 0
while True:
if pir.value() == 1:
motion_count += 1
dist = get_distance()
lcd_write("Motion: " + str(motion_count))
lcd_write("Dist: " + str(dist))
# Check condition
if motion_count > 6 and dist < 5:
delay = 2 # slow blinking
else:
delay = 0.5 # normal speed
# Traffic light sequence
green.on()
red.off()
yellow.off()
time.sleep(delay)
green.off()
yellow.on()
time.sleep(1)
yellow.off()
red.on()
time.sleep(delay)
time.sleep(1)