import network
from machine import Pin
import time
import urequests
ssid = "Wokwi-GUEST"
password = ""
myChannelNumber =
myWriteAPIKey = ""
myReadAPIKey = ""
ledPin1 = Pin(4, Pin.OUT) # GPIO 4 for LED1
ledPin2 = Pin(5, Pin.OUT) # GPIO 5 for LED2
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(ssid, password)
while not wifi.isconnected():
print("Connecting to WiFi...")
time.sleep(1)
print("Connected to WiFi")
def read_from_thingspeak(channel, field, api_key):
url = "https://api.thingspeak.com/channels/{}/fields/{}/last.json?api_key={}".format(channel, field, api_key)
response = urequests.get(url)
data = response.json()
response.close()
return int(data["field{}".format(field)])
def write_to_thingspeak(channel, field, value, api_key):
url = "https://api.thingspeak.com/update?api_key={}&field{}={}".format(api_key, field, value)
response = urequests.get(url)
response.close()
while True:
# Read control values for LEDs from ThingSpeak
led1_control = read_from_thingspeak(myChannelNumber, 1, myReadAPIKey)
led2_control = read_from_thingspeak(myChannelNumber, 2, myReadAPIKey)
# Control LEDs based on the values read from ThingSpeak
ledPin1.value(led1_control)
ledPin2.value(led2_control)
# Update ThingSpeak fields with the current statuses of the LEDs
write_to_thingspeak(myChannelNumber, 1, ledPin1.value(), myWriteAPIKey)
write_to_thingspeak(myChannelNumber, 2, ledPin2.value(), myWriteAPIKey)
time.sleep(20) # Wait for 20 seconds before the next loop iteration