import network
import time
from machine import Pin, ADC
import urequests # Requires 'urequests' library installed on Pico W
# --- ThingSpeak and WiFi Configuration ---
WIFI_SSID = "pi6b" # 1. CHANGE THIS to your WiFi network name
WIFI_PASSWORD = "1234567890" # 2. CHANGE THIS to your WiFi password
THINGSPEAK_API_KEY = "WP1WTNVOAC9LLFUZ" # 3. CHANGE THIS to your ThingSpeak Write API Key
THINGSPEAK_FIELD = 1 # 4. CHANGE THIS if you use a different field (e.g., field2)
UPDATE_INTERVAL_SECONDS = 15 # ThingSpeak free tier has a 15-second minimum update interval
# --- Sensor Configuration ---
# Define the ADC pin connected to the MQ-2 sensor's analog output (A0)
MQ2_PIN = 26
adc = ADC(Pin(MQ2_PIN))
# Set ADC attenuation (optional, usually 0-65535 by default)
# The Pico ADC is 12-bit internally but returns a 16-bit value (0-65535)
# --- Wi-Fi Connection Function ---
def connect_to_wifi():
"""Connects the Pico W to the specified WiFi network."""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
max_wait = 20
while max_wait > 0:
if wlan.isconnected():
print("WiFi Connected!")
print('IP address:', wlan.ifconfig()[0])
return wlan
print("Waiting for WiFi connection...")
time.sleep(1)
max_wait -= 1
print("Error: Could not connect to WiFi.")
return None
# --- Sensor Reading Function ---
def read_mq2_sensor():
"""Reads the raw analog value from the MQ-2 sensor."""
# Read the raw 16-bit value (0-65535)
raw_value = adc.read_u16()
return raw_value
# --- ThingSpeak Update Function ---
def send_to_thingspeak(sensor_value):
"""Sends the sensor value to ThingSpeak via HTTP GET request."""
# Construct the ThingSpeak URL for updating a channel field
url = (
f"https://api.thingspeak.com/update?api_key=WP1WTNVOAC9LLFUZ&field1={raw_value}"
)
print(f"Sending value: {sensor_value} to ThingSpeak...")
try:
response = urequests.get(url)
# ThingSpeak returns the entry ID on success (e.g., '12345') or '0' on failure
if response.status_code == 200 and response.text != '0':
print(f"Update successful. Entry ID: {response.text}")
else:
print(f"ThingSpeak update failed. Status code: {response.status_code}, Response: {response.text}")
response.close() # Always close the response object
return True
except Exception as e:
print(f"HTTP request error: {e}")
return False
# --- Main Application Loop ---
def main():
wlan = connect_to_wifi()
if not wlan:
return
print("Starting data logging to ThingSpeak...")
try:
while True:
if not wlan.isconnected():
print("WiFi lost, attempting to reconnect...")
wlan = connect_to_wifi()
if not wlan:
# If reconnect fails, wait and try again next loop
time.sleep(UPDATE_INTERVAL_SECONDS)
continue
# 1. Read the Sensor
mq2_value = read_mq2_sensor()
print(f"MQ-2 Raw ADC Value: {mq2_value}")
# 2. Send Data to ThingSpeak
send_to_thingspeak(mq2_value)
# 3. Wait for the next update
time.sleep(UPDATE_INTERVAL_SECONDS)
except KeyboardInterrupt:
print("\nProgram stopped by user.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
main()