import machine
import time
import dht
import network
import urequests
from machine import Pin, I2C, ADC
from i2c_lcd import I2cLcd
# Pin definitions
MQPin = ADC(Pin(34))
RED_LED = Pin(5, Pin.OUT)
GREEN_LED = Pin(4, Pin.OUT)
BLUE_LED = Pin(2, Pin.OUT)
sensor = dht.DHT22(Pin(14))
# I2C LCD setup
I2C_ADDR = 0x27
I2C_NUM_ROWS = 2
I2C_NUM_COLS = 16
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=100000)
lcd = None
# WiFi credentials
ssid = "Wokwi-GUEST"
password = ""
# Firebase configurations
API_KEY = "4uPkFkREEXvmzXo6B4xoBUdPEm2gAFvWQdMfSFyA"
DATABASE_URL = "https://gas-leak-esp32-default-rtdb.asia-southeast1.firebasedatabase.app/"
def scan_i2c_devices(i2c):
devices = i2c.scan()
if len(devices) == 0:
print("No I2C devices found!")
else:
print("I2C devices found:", devices)
return devices
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
lcd.clear()
lcd.putstr("Connecting to\n{}".format(ssid))
print("Connecting to WiFi...")
while not wlan.isconnected():
time.sleep(0.5)
lcd.putstr(".")
print(".")
lcd.clear()
ip = wlan.ifconfig()[0]
lcd.putstr("WiFi Connected\nIP: {}".format(ip))
print("WiFi Connected, IP: {}".format(ip))
time.sleep(2)
lcd.clear()
def send_to_firebase(data):
url = "{}/Values.json?auth={}".format(DATABASE_URL, API_KEY)
headers = {"Content-Type": "application/json"}
try:
response = urequests.put(url, json=data, headers=headers)
if response.status_code == 200:
print("Data sent to Firebase successfully")
else:
print("Failed to send data to Firebase")
response.close()
except Exception as e:
print("Error: ", e)
def setup():
global lcd
devices = scan_i2c_devices(i2c)
if I2C_ADDR not in devices:
print("LCD not found at address", I2C_ADDR)
return
lcd = I2cLcd(i2c, I2C_ADDR, I2C_NUM_ROWS, I2C_NUM_COLS)
lcd.putstr(" GAS LEAKAGE\n DETECTOR")
print("GAS LEAKAGE DETECTOR")
time.sleep(2)
lcd.clear()
connect_wifi()
def loop():
while True:
gas_value = MQPin.read()
print("Gas Value: {}".format(gas_value))
try:
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
print("Temperature: {}°C".format(temperature))
print("Humidity: {}%".format(humidity))
except Exception as e:
print("Failed to read from DHT sensor:", e)
temperature = None
humidity = None
if gas_value > 1000:
GREEN_LED.off()
BLUE_LED.on()
for _ in range(5):
RED_LED.on()
time.sleep(0.2)
RED_LED.off()
time.sleep(0.2)
lcd.clear()
lcd.putstr(" GAS DETECTED\n WARNING!!!")
print("GAS DETECTED WARNING!!!")
time.sleep(1)
else:
RED_LED.off()
GREEN_LED.on()
BLUE_LED.off()
lcd.clear()
lcd.putstr(" NO GAS\n DETECTED")
print("NO GAS DETECTED")
time.sleep(1)
if temperature is not None and humidity is not None:
lcd.clear()
print("Temperature: {}°C".format(temperature))
print("Humidity: {}%".format(humidity))
time.sleep(2)
data = {
"gas_value": gas_value,
"temperature": temperature,
"humidity": humidity,
}
send_to_firebase(data)
time.sleep(2)
setup()
loop()