# modules

from machine import Pin, PWM
from time import sleep
from dht import DHT22
from pico_i2c_lcd import I2cLcd

# Setup Servo Motor
pwm = PWM(Pin(15))
pwm.freq(50)
min_duty = 1700
max_duty = 10250
min_degrees = 0
max_degrees = 180

def degrees_to_duty(degrees):
    duty_step = ((max_duty - min_duty) / max_degrees)
    if degrees > max_degrees:
        degrees = max_degrees
    elif degrees < min_degrees:
        degrees = min_degrees
    duty = int((duty_step * degrees) + min_duty)
    if duty > max_duty:
        duty = max_duty
    elif duty < min_duty:
        duty = min_duty
    return duty

def set_servo_position(degrees):
    duty = degrees_to_duty(degrees)
    pwm.duty_u16(duty)

# Connect Keypad pins
col_list = [1, 2, 3, 4]
row_list = [5, 6, 7, 8]

for x in range(4):
    row_list[x] = Pin(row_list[x], Pin.OUT)
    row_list[x].value(1)

for x in range(4):
    col_list[x] = Pin(col_list[x], Pin.IN, Pin.PULL_UP)

key_map = [["D", "#", "0", "*"],
           ["C", "9", "8", "7"],
           ["B", "6", "5", "4"],
           ["A", "3", "2", "1"]]

def Keypad4x4Read(cols, rows):
    for r in rows:
        r.value(0)
        result = [cols[0].value(), cols[1].value(), cols[2].value(), cols[3].value()]
        if min(result) == 0:
            key = key_map[int(rows.index(r))][int(result.index(0))]
            r.value(1)
            return key
        r.value(1)

# Motion Sensor and LED
motion_sensor_pin = Pin(11, Pin.IN)
led_pin = Pin(12, Pin.OUT)

# Setup DHT sensor
dht = DHT22(Pin(26))

# Setup LCD
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
I2C_ADDR = i2c.scan()[0]
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)

# Setup Buzzer
buzzer = PWM(Pin(22))

# Main loop
print("--- Ready to get user inputs and detect motion ---")
while True:
    # Getting DHT sensor readings
    dht.measure()
    temp = dht.temperature()
    hum = dht.humidity()

    # Displaying DHT sensor readings on LCD
    lcd.putstr(f" Temp: {temp}°C Humty: {hum}% ")
    sleep(5)  # Display for 5 seconds
    lcd.clear()
    sleep(1)  # Clear for 1 second then print again

    # Check conditions for buzzer activation
    if temp > 20 or hum > 30:
        buzzer.freq(500)
        buzzer.duty_u16(1000)
        sleep(1)
        buzzer.duty_u16(0)

    # Keypad input handling
    key = Keypad4x4Read(col_list, row_list)
    if key is not None:
        print("Pressed button:", key)
        if key == "1":
            set_servo_position(35)
        elif key == "4":
            set_servo_position(65)
        elif key == "7":
            set_servo_position(100)
        elif key == "D":
            set_servo_position(135)
        elif key == "0":
            set_servo_position(0)
        sleep(0.3)

    # Motion detection
    if motion_sensor_pin.value() == 1:
        print("Motion detected!")
        led_pin.on()
        sleep(1)
    else:
        print("No motion detected!")
        led_pin.off()
        sleep(1)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT