from machine import Pin
from mq2 import MQ2
from picozero import Speaker
from time import sleep, ticks_ms, ticks_diff
import urequests
import network
ssid = "Wokwi-GUEST"
password = ""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
print("Connecting")
pass
if wlan.isconnected():
print("Connected")
write_api_key = "9T55Y4V145AES9H7"
url = "https://api.thingspeak.com/update"
# Link to ThingSpeak dashboard
# https://thingspeak.mathworks.com/channels/3258549
last_send = 0
threshold = 30 # Threshold for methane leakage
mq2Pin = 26
redPin = Pin(12, Pin.OUT)
greenPin = Pin(11, Pin.OUT)
bluePin = Pin(10, Pin.OUT)
sensor = MQ2(pinData = mq2Pin, baseVoltage = 3.3)
speaker = Speaker(9)
redPin.value(0)
greenPin.value(0)
bluePin.value(0)
speaker.off()
print("Calibrating")
sensor.calibrate()
print("Calibration completed")
print("Base resistance:{0}".format(sensor._ro))
while True:
if last_send is 0:
last_send = ticks_ms()
methaneConc = sensor.readMethane()
# Send req to thingspeak every 16 sec
if ticks_diff(ticks_ms(), last_send) > 16000:
try:
response = urequests.get(f"{url}?api_key={write_api_key}&field1={methaneConc}")
if response.status_code == 200:
print("Data sent to ThingSpeak!!!")
except Exception as e:
print(f"Error: {e}")
finally:
response.close()
last_send = 0
pass
if methaneConc > threshold:
redPin.value(1)
greenPin.value(0)
bluePin.value(0)
speaker.on();
else:
redPin.value(0)
greenPin.value(1)
bluePin.value(0)
speaker.off()
print(f"Methane Concentration: {methaneConc:.2f}")
sleep(0.5)