import machine
import time
import ssd1306 # OLED library
import dht
# Pin definitions
DHT_PIN = 15 # DHT22 data pin
BUTTON_PIN = 4 # Push button for reset
LED_PIN = 2 # LED pin
BUZZER_PIN = 5 # Buzzer pin
I2C_SDA = 21 # I2C SDA pin for OLED
I2C_SCL = 22 # I2C SCL pin for OLED
# Setup DHT22
dht_sensor = dht.DHT22(machine.Pin(DHT_PIN))
# Setup button
button = machine.Pin(BUTTON_PIN, machine.Pin.IN, machine.Pin.PULL_UP) # Use pull-up resistor
# Setup LED
led = machine.Pin(LED_PIN, machine.Pin.OUT)
# Setup I2C for OLED
i2c = machine.I2C(0, scl=machine.Pin(I2C_SCL), sda=machine.Pin(I2C_SDA), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Setup PWM for Buzzer
buzzer = machine.PWM(machine.Pin(BUZZER_PIN), freq=1000, duty=0) # Start with duty cycle 0 (off)
def display_message(message):
oled.fill(0) # Clear OLED
for i, line in enumerate(message):
oled.text(line, 0, i * 10) # Display each line with a vertical offset
oled.show()
def turn_off_alarm():
led.off()
buzzer.duty(0) # Turn off the buzzer
def play_sound(frequency, duration):
buzzer.freq(frequency) # Set the frequency for the buzzer
buzzer.duty(512) # Set duty cycle to 50%
time.sleep(duration) # Play sound for the specified duration
buzzer.duty(0) # Turn off the buzzer
def alarm_system():
alarm_active = False # Flag to indicate if the alarm is currently active
# Allow some time for the sensor to stabilize
time.sleep(2)
while True: # Corrected the while loop syntax
dht_sensor.measure()
temperature = dht_sensor.temperature()
print("Temperature:", temperature)
# Check temperature thresholds
if temperature is not None: # Ensure the temperature reading is valid
if temperature > 70: # Threshold for high temperature
if not alarm_active: # Only activate alarm if it's not already active
alarm_active = True
display_message([
"EXIT THIS WAY!",
" =======>",
" FIRE!!!",
"PLEASE DON'T ",
" BE PANIC!"
])
led.on()
play_sound(1000, 0.5) # Play sound at 1kHz
print("Alarm activated!") # Debugging statement
else: # If temperature is below or equal to 70
if alarm_active: # If alarm was active, reset it
alarm_active = False # Reset alarm state
led.off() # Ensure LED is off
buzzer.duty(0) # Ensure buzzer is off
display_message(["HAVE A NICE DAY!"]) # Display reset message
time.sleep(1) # Short delay to show message
print("Alarm deactivated!") # Debugging statement
# Check for reset button
if not button.value(): # Check if the button is pressed
turn_off_alarm() # Turn off the buzzer and LED
alarm_active = False # Reset alarm state to allow re-triggering
display_message(["System Shut Down"]) # Optionally display a message
time.sleep(1) # Debounce delay
print("Alarm turned off by button!") # Debugging statement
time.sleep(2) # Delay before the next reading
# Start the alarm system
alarm_system()