print("Developed by: HANNAN")
print("Date: 22/4/2025")
#Import library/module
from machine import Pin, ADC, PWM, SoftI2C
import dht
import oled
import door_sensor
from time import sleep
#Pin Declaration
dht_sensor = dht.DHT22(Pin(26))
mq2_sensor = ADC(Pin(34))
mq2_sensor.atten(ADC.ATTN_11DB) # 0–3.3V range
red_led = Pin(19, Pin.OUT)
blue_led = Pin(17, Pin.OUT)
white_led = Pin(15, Pin.OUT)
buzzer = PWM(Pin(16))
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
servo_pin = 18
button_open = Pin(4, Pin.IN, Pin.PULL_UP)
button_close = Pin(5, Pin.IN, Pin.PULL_UP)
#object Declaration
screen = oled.SSD1306_I2C(width=128, height=64, i2c=i2c)
servo = PWM(Pin (servo_pin), freq=50)
servo = PWM(Pin(18), freq=50)
door_sensor_pin = 4
servo_close = 0
servo_open= 90
door_sensor = Pin(door_sensor_pin, Pin.IN, Pin.PULL_UP)
def set_servo_angle(angle):
duty = int((angle / 180) * 102 + 26)
servo.duty(duty)
#Parameter Declaration
set_servo_angle(servo_close)
#Main Program
while True:
# Read DHT22 sensor
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
# Read MQ2 sensor and convert to voltage
gas_value = mq2_sensor.read()
voltage = gas_value / 4095 * 3.3
# Print to console
print("Temp: {:.1f}C, Humidity: {:.1f}%, Gas: {:.2f}V".format(temperature, humidity, voltage))
# OLED display
screen.fill(0)
screen.text("Temp: {:.1f}C".format(temperature), 0, 0, 1)
screen.text("Humidity: {:.1f}%".format(humidity), 0, 10, 1)
screen.text("Gas: {:.2f}V".format(voltage), 0, 20, 1)
# Temperature alert
if temperature >= 30:
screen.text("ITS DANGEROUS ", 0, 35, 1)
red_led.on()
buzzer.init(freq=5000, duty=1023)
else:
red_led.off()
# Humidity alert
if humidity >= 70:
screen.text("VERY UNSAFE", 0, 45, 1)
blue_led.on()
buzzer.init(freq=800, duty=512)
else:
blue_led.off()
white_led.off()
# Gas alert
if voltage >= 1.5:
screen.text("⚠ Gas Detected!!", 0, 45, 1)
white_led.on()
buzzer.init(freq=1000, duty=512)
elif temperature < 30 and humidity < 70 and voltage < 1.5:
#screen.text("ALL GOOD", 0, 45, 1)
#buzzer.init(freq=800, duty=0)
#servo motor
if button_open.value() == 1:
set_servo_angle(90)
red_led.on()
blue_led.on()
white_led.on()
buzzer.init(freq=1000, duty=512)
screen.fill(0)
screen.text("CLOSE THE DOOR!", 0, 45,1)
screen.show()
sleep(0.5)
elif button_close.value() == 0:
set_servo_angle(0)
red_led.off()
blue_led.off()
white_led.off()
buzzer.init(freq=800, duty=0)
screen.fill(0)
screen.text("DOOR CLOSE", 0, 45,1)
screen.show()
sleep(0.5)
sleep(0.2)
screen.show()
sleep(5)