import time
from machine import Pin, PWM, ADC, I2C
from ssd1306 import SSD1306_I2C
from picozero import Servo, LED
import dht
# Initialize components
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
oled = SSD1306_I2C(128, 64, i2c)
servo = Servo(16)
button = Pin(14, Pin.IN, Pin.PULL_DOWN) # Use a different pin for the button
potentiometer1 = ADC(Pin(26))
potentiometer2 = ADC(Pin(27))
buzzer = PWM(Pin(15))
led7 = LED(7)
led8 = LED(8)
led9 = LED(9)
led10 = LED(20)
led11 = LED(17)
led12 = LED(18)
led13 = LED(19)
pir_sensor = Pin(5, Pin.IN)
dht_sensor = dht.DHT22(Pin(4))
# Function to play a tone
def play_tone(frequency, duration):
buzzer.freq(frequency)
buzzer.duty_u16(32768) # 50% duty cycle
time.sleep(duration)
buzzer.duty_u16(0) # Turn off the buzzer
# Main loop
try:
while True:
# Read potentiometer values
reading1 = potentiometer1.read_u16()
reading2 = potentiometer2.read_u16()
print(f"Pot1: {reading1}, Pot2: {reading2}")
# Control LEDs based on potentiometer1 value (subs for gas sensor 1 - outside house)
if 0 <= reading1 < 20000:
led7.on()
led8.off()
led9.off()
elif 20000 <= reading1 < 40000:
led7.off()
led8.on()
led9.off()
else:
led7.off()
led8.off()
led9.on()
# Control LEDs based on potentiometer2 value (subs for gas sensor 2 - inside house)
if 0 <= reading2 < 20000:
led10.off()
led11.on()
led12.off()
led13.off()
elif 20000 <= reading2 < 40000:
led10.off()
led11.off()
led12.on()
led13.off()
else:
led10.on()
led11.off()
led12.off()
led13.on()
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
print(f"Temp: {temperature} C, Humidity: {humidity} %")
# Display message on OLED based on potentiometer values
oled.fill(0)
oled.text(f"Pot1: {reading1}", 0, 0)
oled.text(f"Pot2: {reading2}", 0, 10)
oled.text(f"Temp: {temperature}C", 0, 20)
oled.text(f"Hum: {humidity}%", 0, 30)
# Servo control logic (to shut down gas valve)
if reading1 >= 40000:
oled.text("GAS DETECTED (O)", 0, 40)
servo.max()
elif 20000 <= reading1 < 40000:
oled.text("WARNING (O)", 0, 40)
else:
oled.text("NO GAS (O)", 0, 40)
servo.mid()
if reading2 >= 40000:
oled.text("GAS DETECTED (I)", 0, 50)
led10.on()
servo.max()
elif 20000 <= reading2 < 40000:
oled.text("WARNING (I)", 0, 50)
else:
oled.text("NO GAS (I)", 0, 50)
servo.mid()
# Play buzzer tone based on potentiometer values (subs for ventilation system)
if reading1 >= 40000:
play_tone(1000, 0.5) # Tone for potentiometer1 high range
if reading2 >= 40000:
play_tone(1500, 0.5) # Tone for potentiometer2 high range
oled.show()
# Check PIR sensor for motion
if pir_sensor.value() == 1:
oled.fill(0)
oled.text("MOTION DETECTED!", 0, 0)
oled.show()
play_tone(2000, 0.5)
time.sleep(1)
time.sleep(1)
except KeyboardInterrupt:
buzzer.duty_u16(0) # Ensure buzzer is turned off when exiting