from machine import I2C, Pin, PWM, ADC
from utime import sleep
import dht
import utime
from pico_i2c_lcd import I2cLcd
# Initialize I2C for LCD
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
I2C_ADDR = 0x27
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
lcd.backlight_on()
# Initialize Light Dependent Resistor (LDR)
LDR = ADC(28)
pwm = PWM(Pin(15))
pwm.freq(1000)
# Initialize Ultrasonic Sensor pins
TRIGGER_PIN = Pin(3, Pin.OUT)
ECHO_PIN = Pin(4, Pin.IN)
# Initialize Motion Sensor pin
MOTION_PIN = Pin(16, Pin.IN)
# Initialize LED for motion detection
LED = Pin(2, Pin.OUT)
# Initialize DHT22 sensor
sensor = dht.DHT22(Pin(5))
def distance():
TRIGGER_PIN.on()
sleep(0.00001)
TRIGGER_PIN.off()
while not ECHO_PIN.value():
pass
pulse_start = utime.ticks_us()
while ECHO_PIN.value():
pass
pulse_end = utime.ticks_us()
pulse_duration = utime.ticks_diff(pulse_end, pulse_start)
distance_cm = pulse_duration / 58.0
return distance_cm
while True:
try:
# Temperature and Humidity measurement
sensor.measure()
lcd.clear()
lcd.putstr(f"Temp: {sensor.temperature():.1f}")
lcd.move_to(0, 1)
lcd.putstr(f"Humidity: {sensor.humidity():.1f}")
sleep(5)
# Distance measurement
dist = distance()
lcd.clear()
lcd.putstr(f"Distance: {dist:.2f} cm")
sleep(5)
# Light Intensity measurement
value = LDR.read_u16()
lcd.clear()
lcd.putstr("Light Intensity: {}".format(value))
pwm.duty_u16(value)
if value < 5000:
print("low")
sleep(0.001)
elif value > 5000:
print("better")
sleep(0.001)
sleep(5)
# Motion detection
lcd.clear()
if MOTION_PIN.value():
lcd.putstr("Motion Detected")
else:
lcd.putstr("No Motion")
sleep(5)
except OSError as e:
lcd.putstr('Failed reception')