from machine import I2C, Pin, PWM
from time import sleep
from pico_i2c_lcd import I2cLcd
import dht
# DHT22 sensor setup
dSensor = dht.DHT22(Pin(0))  # Adjust the pin as needed
# LED Pins setup
red_led = Pin(16, Pin.OUT)
green_led = Pin(15, Pin.OUT)
yellow_led = Pin(17, Pin.OUT)
# Buzzer setup
buzzer = PWM(Pin(28, Pin.OUT))
# Buzzer control functions
def beep(frequency, duration):
    buzzer.freq(frequency)
    buzzer.duty_u16(32768)  # Set duty cycle for volume (approx. 50%)
    sleep(duration)
    buzzer.duty_u16(0)  # Turn buzzer off
def alert_beep():
    for _ in range(10):  # Repeat for emphasis
        beep(980, 0.5)  # High-pitched beep
        sleep(0.2)
# I2C LCD initialization
def initialize_i2c_lcd(sda_pin, scl_pin, i2c_freq):
    """Initialize the I2C LCD display with the given parameters."""
    i2c_bus = I2C(0, sda=Pin(sda_pin), scl=Pin(scl_pin), freq=i2c_freq)
    i2c_address = i2c_bus.scan()[0]  # Find the I2C address
    lcd = I2cLcd(i2c_bus, i2c_address, 2, 16)
    lcd.clear()
    lcd.blink_cursor_off()
    return lcd, i2c_address, i2c_bus
# Read DHT22 data
def read_dht():
    """Read temperature and humidity from the DHT sensor."""
    try:
        dSensor.measure()
        temp = dSensor.temperature()
        temp_f = (temp * (9/5)) + 32.0
        hum = dSensor.humidity()
        return temp, hum
    except OSError as e:
        print('Failed to read data from DHT sensor')
        return None, None 
# Display data on the LCD
def print_dht_data(lcd, i2c_bus):
    """Display temperature and humidity on the LCD."""
    temp, hum = read_dht()
    if temp is not None and hum is not None:
        lcd.clear()
        lcd.putstr("Temp:")
        lcd.putstr(str(int(temp)) + "C")
        lcd.putstr("\nHumidity:")
        lcd.putstr(str(int(hum)) + "%")
        sleep(1)  # Delay to reduce flickering
# Main program loop
def main():
    lcd_display, i2c_address, i2c_bus = initialize_i2c_lcd(sda_pin=4, scl_pin=1, i2c_freq=400000)  
    while True:
        temp, hum = read_dht()
        if temp is not None and hum is not None:
            if temp < 28:
                green_led.on()
                yellow_led.off()
                red_led.off()
                buzzer.duty_u16(0)  # Ensure buzzer is off
            elif 28 <= temp < 37:
                green_led.off()
                yellow_led.on()
                red_led.off()
                buzzer.duty_u16(0)  # Ensure buzzer is off
            else:  # temp >= 37
                green_led.off()
                yellow_led.off()
                red_led.on()
                alert_beep()  # Trigger alert beeps
        print_dht_data(lcd_display, i2c_bus)
        sleep(2)  # Update interval
if __name__ == '__main__':
    main()