from machine import ADC, Pin
from time import sleep
import network
import urequests
# Wi-Fi credentials
SSID = "Wokwi-GUEST"
PASSWORD = ""
# ThingSpeak API key and URL
THINGSPEAK_API_KEY = "73D4FM7DNHLIVNJ2"
THINGSPEAK_URL = "https://thingspeak.com/channels/2660070/private_show"
# Setup the hardware
LED_green = Pin(16, Pin.OUT)
LED_red = Pin(17, Pin.OUT)
buzzer = Pin(18, Pin.OUT)
AnalogIn = ADC(Pin(34)) # ADC channel 0 on ESP32
AnalogIn.atten(ADC.ATTN_11DB) # Full range: 0-3.3V
Conv = 3.3 / 4095 # Conversion factor for 12-bit ADC
# Function to connect to Wi-Fi
def connect_to_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
print("Connecting to Wi-Fi...")
sleep(1)
print("Connected to Wi-Fi:", wlan.ifconfig())
# Function to send data to ThingSpeak
def send_to_thingspeak(gas_value):
try:
response = urequests.get(f"{THINGSPEAK_URL}?api_key={THINGSPEAK_API_KEY}&field1={gas_value}")
print("Data sent to ThingSpeak:", response.text)
response.close()
except Exception as e:
print("Failed to send data:", e)
# Connect to Wi-Fi
connect_to_wifi(SSID, PASSWORD)
# Main loop
while True:
sensor_value = AnalogIn.read() # Read gas sensor value (12-bit ADC)
gas_value = sensor_value * Conv # Convert to volts
print("Gas Value:", gas_value)
# Send the gas value to ThingSpeak
send_to_thingspeak(gas_value)
# Gas value conditions
if gas_value < 1:
buzzer.off()
LED_green.on()
LED_red.off()
sleep(0.1)
LED_green.off()
LED_red.off()
elif 1 <= gas_value < 3:
buzzer.off()
LED_green.off()
LED_red.on()
sleep(0.1)
LED_green.off()
LED_red.off()
elif gas_value >= 3:
buzzer.on()
LED_red.on()
sleep(0.1)
buzzer.off()
LED_red.off()
# Additional changes: Add warning message
if gas_value > 2.5:
print("Warning: High gas concentration detected!")
sleep(1) # Wait for 1 second before next reading