from machine import Pin, I2C
from time import sleep
import time
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
# Pin Configuration
PIR_PIN = 14 # GPIO pin for PIR motion sensor
TRIG_PIN = 12 # GPIO pin for ultrasonic sensor trigger
ECHO_PIN = 13 # GPIO pin for ultrasonic sensor echo
LED_PIN = 2 # GPIO pin for LED
# I2C Configuration for LCD
I2C_ADDR = 0x27 # I2C address for LCD
I2C_SDA = 21 # GPIO pin for I2C SDA
I2C_SCL = 22 # GPIO pin for I2C SCL
# Distance Threshold (in cm)
DISTANCE_THRESHOLD = 100
# Setup GPIO Pins
pir = Pin(PIR_PIN, Pin.IN)
led = Pin(LED_PIN, Pin.OUT)
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
# Setup I2C and LCD
i2c = I2C(1, scl=Pin(I2C_SCL), sda=Pin(I2C_SDA), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, 4, 20) # 4x20 LCD
# Function to measure distance using ultrasonic sensor
def measure_distance():
# Trigger a pulse
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
# Measure echo pulse duration
while echo.value() == 0:
start = time.ticks_us()
while echo.value() == 1:
end = time.ticks_us()
# Calculate distance
duration = time.ticks_diff(end, start)
distance = (duration * 0.0343) / 2 # Speed of sound: 343 m/s
return distance
# Main loop
try:
lcd.putstr("Smart Lighting\nInitializing...")
time.sleep(2)
lcd.clear()
lcd.putstr("Waiting for motion...")
while True:
motion_detected = pir.value() # Read PIR sensor
distance = measure_distance() # Measure distance
lcd.clear()
lcd.putstr(f"Motion: {'Yes' if motion_detected else 'No'}\n")
lcd.putstr(f"Distance: {distance:.1f} cm\n")
if motion_detected and distance <= DISTANCE_THRESHOLD:
# Turn on the light
led.value(1)
lcd.putstr("Light: ON ")
else:
# Turn off the light
led.value(0)
lcd.putstr("Light: OFF")
time.sleep(0.5)
except KeyboardInterrupt:
print("Program stopped")
lcd.clear()