from machine import Pin, I2C, PWM
import ssd1306
import dht
from time import sleep
# Pin definitions
buzzer_pin = 25 # Pin connected to buzzer
servo_pin = 18 # Pin connected to servo motor
dht_pin = 27 # Pin connected to DHT sensor
relay_pin = 14 # Pin connected to relay module
# Initialize , servo motor, SSD1306 OLED display and buzzer
servo = PWM(Pin(servo_pin), freq=50, duty=77)
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=10000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
buzzer = PWM(Pin(buzzer_pin), freq=10000, duty=0)
# Initialize DHT sensor
dht_sensor = dht.DHT22(Pin(dht_pin))
# Function to read temperature and humidity from DHT sensor
def read_sensor():
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
return temperature, humidity
# Function to control the relay (turn on/off exhaust fan)
def control_fan(state):
fan_pin = Pin(relay_pin, 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.duty(500)
sleep(0.1)
buzzer.duty(0)
# Main loop
while True:
# Read temperature and humidity
temp, humid = read_sensor()
# Display temperature and humidity on OLED display
oled.fill(1)
oled.text("Temp: {:.1f} C".format(temp),5, 10, 0)
oled.text("Humidity: {:.1f}%".format(humid),5, 20, 0)
oled.show()
print("Temperature: {:.1f} C".format(temp))
print("Humidity: {:.1f}%".format(humid))
# Check if temperature or humidity exceeds thresholds
if temp > 30 or humid > 60:
# Turn on fan and open shutter
control_fan(1) # State relay on
adjust_servo(270) # Open shutter fully
#display fan shutter open
oled.text("-----------------", 0, 30, 0)
oled.text("FAN OPEN !!", 5, 40, 0)
oled.text("-----------------", 0, 50, 0)
oled.show()
buzz() # Sound buzzer for alert
else:
# Turn off fan and close shutter
control_fan(0) # State relay off
adjust_servo(0) # Close shutter fully
#display fan shutter closed
oled.text("-----------------", 0, 30, 0)
oled.text("FAN CLOSED!!", 5, 40, 0)
oled.text("-----------------", 0, 50, 0)
oled.show()
buzzer.duty(0)
# Delay before next reading
sleep(900)