from machine import Pin
import network
import urequests
import time
# Wi-Fi Credentials
SSID = "Wokwi-GUEST"
PASSWORD = ""
# ThingSpeak Write API Key
API_KEY = "LS6G4Y7GBRKOGTKO"
# LED and Button
led = Pin(8, Pin.OUT)
button = Pin(10, Pin.IN, Pin.PULL_UP)
# Connect to Wi-Fi
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(SSID, PASSWORD)
print("Connecting to Wi-Fi...")
while not wifi.isconnected():
time.sleep(1)
print("Connected!")
print(wifi.ifconfig())
led_state = False
last_button_state = 1
while True:
current_button_state = button.value()
# Detect button press
if last_button_state == 1 and current_button_state == 0:
led_state = not led_state
if led_state:
led.on()
status = 1
print("LED ON")
else:
led.off()
status = 0
print("LED OFF")
# Send data to ThingSpeak
try:
url = "https://api.thingspeak.com/update?api_key={}&field1={}".format(API_KEY, status)
response = urequests.get(url)
print("ThingSpeak Response:", response.text)
response.close()
except Exception as e:
print("Error:", e)
time.sleep(0.2) # Debounce
last_button_state = current_button_state