from machine import Pin, I2C, PWM
import machine
import dht
import ssd1306
import time

# Pin definitions
DHT_PIN = 4  # Pin connected to DHT22 sensor
RELAY_PIN = 5  # Pin connected to relay module
SERVO_PIN = 14  # Pin connected to servo motor
BUZZER_PIN = 12  # Pin connected to buzzer

# Initialize DHT sensor
dht_sensor = dht.DHT22(machine.Pin(DHT_PIN))

# Initialize SSD1306 OLED display
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=10000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)

# Initialize servo motor
servo = machine.PWM(machine.Pin(SERVO_PIN), freq=50)
servo.duty(77)  # Initial position for servo (adjust according to your servo)

# Initialize buzzer
buzzer = machine.Pin(BUZZER_PIN, machine.Pin.OUT)

# Function to read temperature and humidity from DHT sensor
def read_dht():
    dht_sensor.measure()
    return dht_sensor.temperature(), dht_sensor.humidity()

# Function to control the relay (turn on/off exhaust fan)
def control_fan(state):
    fan_pin = machine.Pin(RELAY_PIN, machine.Pin.OUT)
    fan_pin.value(state)

# Function to adjust servo position (open/close fan shutter)
def adjust_servo(angle):
    duty = 77 + int(angle / 18)  # Map angle to servo duty
    servo.duty(duty)

# Function to sound buzzer
def buzz():
    buzzer.on()
    time.sleep(0.1)
    buzzer.off()

# Main loop
while True:
    # Read temperature and humidity
    temp, humidity = read_dht()
    
    # Display temperature and humidity on OLED display
    oled.fill(0)
    oled.text("Temp: {:.1f} C".format(temp), 0, 0)
    oled.text("Humidity: {:.1f}%".format(humidity), 0, 20)
    oled.show()
    
    # Check if temperature or humidity exceeds thresholds
    if temp > 30 or humidity > 60:
        # Turn on fan and open shutter
        control_fan(1)
        adjust_servo(90)  # Open shutter fully
        buzz()  # Sound buzzer for alert
    else:
        # Turn off fan and close shutter
        control_fan(0)
        adjust_servo(0)  # Close shutter fully
    
    # Delay before next reading
    time.sleep(2)
NOCOMNCVCCGNDINLED1PWRRelay Module