import network
import urequests # For HTTP requests
from machine import Pin, I2C, Timer
import ssd1306
import time
# BME280 library import (ensure it's uploaded to your device)
from BME280 import BME280
# Wi-Fi credentials
WIFI_SSID = 'Fadil_Rex_2.4G@unifi'
WIFI_PASS = 'Alifnajmi51'
# ThingSpeak API settings
THINGSPEAK_WRITE_API_KEY = '9W5B37EEXR6B76E6'
THINGSPEAK_CHANNEL_URL = 'https://api.thingspeak.com/update?api_key=NZ755XO0L75U6APS&field1=0'
# Initialize I2C (adjust the pins according to your ESP model)
i2c = I2C(scl=Pin(22), sda=Pin(21))
# Initialize BME280 sensor
bme280 = BME280(i2c=i2c)
# Initialize OLED display
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Initialize the buzzer (replace '...' with your buzzer pin)
buzzer = Pin(14, Pin.OUT)
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to network...')
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
pass
print('WiFi connected')
def beep(duration_ms):
buzzer.on()
time.sleep_ms(duration_ms)
buzzer.off()
def send_to_thingspeak(temperature):
try:
url = f'{THINGSPEAK_CHANNEL_URL}?api_key={THINGSPEAK_WRITE_API_KEY}&field1={temperature}'
response = urequests.get(url)
print('Data sent to ThingSpeak')
except Exception as e:
print('Failed to send data to ThingSpeak:', e)
finally:
response.close()
def read_sensors():
temperature, pressure, humidity = bme280.read_compensated_data()
return temperature / 100 # Convert to Celsius
def update_display(temperature):
oled.fill(0)
oled.text(f'Temp: {temperature:.2f}C', 0, 0)
oled.show()
def check_temperature(temperature):
if 20 <= temperature <= 25:
oled.text('Comfortable', 0, 10)
return 30000 # 30 seconds
elif 25 < temperature <= 30:
oled.text('Warning', 0, 10)
return 10000 # 10 seconds
elif 31 <= temperature <= 40:
oled.text('Bad Air Quality', 0, 10)
return 2000 # 2 seconds
else:
return None
def main(timer):
temperature = read_sensors()
update_display(temperature)
beep_duration = check_temperature(temperature)
if beep_duration:
beep(200) # Beep for 200 milliseconds
timer.init(period=beep_duration, mode=Timer.ONE_SHOT, callback=main)
else:
timer.init(period=2000, mode=Timer.ONE_SHOT, callback=main) # Default 2 seconds before re-check
send_to_thingspeak(temperature)
connect_wifi()
timer = Timer(-1)