from machine import Pin
from utime import sleep_us, sleep_ms, ticks_us
from machine import I2C
from pico_i2c_lcd import I2cLcd
# Define the pins for ultrasonic sensor
TRIGGER_PIN = 2
ECHO_PIN = 3
# Define the pin for PIR sensor
PIR_PIN = 4
# Define LCD settings
LCD_COLS = 20
LCD_ROWS = 4
# Initialize I2C for LCD
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
I2C_ADDR = i2c.scan()[0]
lcd = I2cLcd(i2c, I2C_ADDR, LCD_ROWS, LCD_COLS)
# Function to measure distance using ultrasonic sensor
def measure_distance():
trigger = Pin(TRIGGER_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
trigger.low()
sleep_us(2)
trigger.high()
sleep_us(10)
trigger.low()
while echo.value() == 0:
pass
time_start = ticks_us()
while echo.value() == 1:
pass
time_end = ticks_us()
time_elapsed = time_end - time_start
distance_cm = (time_elapsed / 2) / 29.1
return distance_cm
# Function to detect motion using PIR sensor
def detect_motion():
pir_pin = Pin(PIR_PIN, Pin.IN)
return pir_pin.value()
# Main loop
i = 0
while True:
# Measure distance
distance = measure_distance()
# Print distance to LCD
lcd.move_to(0, 0)
lcd.putstr("Distance: {:.2f} cm".format(distance))
# Detect motion
motion_detected = detect_motion()
# Print motion detection status to LCD
lcd.move_to(0, 1)
lcd.putstr("Motion: {}".format("Detected" if motion_detected else "None"))
sleep_ms(1000) # Wait for 1 second before next iteration