from machine import Pin, PWM, ADC, I2C
from utime import sleep
from lcd_api import LcdApi
from pico_i2c_lcd import I2cLcd
import dht
import utime
# Initialize I2C for LCD
I2C_ADDR = 0x27
I2C_NUM_ROWS = 2
I2C_NUM_COLS = 16
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, I2C_NUM_ROWS, I2C_NUM_COLS)
lcd.backlight_on()
# Initialize LDR sensor
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 pin
LED = Pin(2, Pin.OUT)
# Initialize DHT sensor
sensor = dht.DHT22(Pin(5))
# Initialize servo motor on pin 14
servo_pin = PWM(Pin(15))
servo_pin.freq(50) # 50 Hz for servo motor
def set_servo_angle(angle):
min_duty = 1000 # Corresponds to 0.5ms
max_duty = 9000 # Corresponds to 2.5ms
duty = int(min_duty + (max_duty - min_duty) * (angle / 180.0))
servo_pin.duty_u16(duty * 65535 // 10000)
print(f"Servo angle set to {angle} degrees with duty {duty}")
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
def ledBlink():
LED.on()
sleep(5)
LED.off()
sleep(5)
while True:
try:
# Measure temperature and humidity
sensor.measure()
lcd.clear()
lcd.putstr(f"Temp: {sensor.temperature():.1f}C")
lcd.move_to(0, 1)
lcd.putstr(f"Humidity: {sensor.humidity():.1f}%")
sleep(5)
# Measure distance
dist = distance()
lcd.clear()
lcd.putstr(f"Distance: {dist:.2f} cm")
print(f"Distance measured: {dist:.2f} cm")
# Control the servo based on distance
if dist <= 20:
set_servo_angle(0)
# Open the servo
else:
set_servo_angle(90) # Close the servo
sleep(5)
# Measure light intensity
value = LDR.read_u16()
lcd.clear()
lcd.putstr("Light Intensity: {}".format(value))
pwm.duty_u16(value)
if value < 5000:
print("Light intensity: low")
elif value > 5000:
print("Light intensity: better")
sleep(5)
# Detect motion
lcd.clear()
if MOTION_PIN.value():
lcd.putstr("Motion Detected")
print("Motion detected")
else:
lcd.putstr("No Motion")
print("No motion detected")
sleep(5)
except OSError as e:
lcd.clear()
lcd.putstr('Failed reception')
print(f"Error: {e}")
sleep(5)