import machine
import time
import urequests
import network
import ujson
# ThingSpeak settings
THINGSPEAK_API_KEY = "97BW7JVYIVEQUNDV"
THINGSPEAK_URL = "http://api.thingspeak.com/update"
# Wi-Fi settings
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# Red LED pin
RED_LED_PIN = machine.Pin(15, machine.Pin.OUT)
# Initialize the Wi-Fi connection
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASSWORD)
# Wait for the Wi-Fi connection to establish
while not wifi.isconnected():
time.sleep(1)
print("Connected to Wi-Fi")
# Function to control the red LED
def control_red_led(state):
RED_LED_PIN.value(state)
# Function to send data to ThingSpeak
def send_data_to_thingspeak(led_state):
data = {
"api_key": THINGSPEAK_API_KEY,
"field1": led_state
}
response = urequests.post(THINGSPEAK_URL, data=ujson.dumps(data), headers={"Content-Type": "application/json"})
response.close()
# Function to process TalkBack commands
def process_talkback_commands():
# Retrieve TalkBack commands
# Replace this section with the code to fetch commands from the platform (e.g., using MQTT, HTTP request)
# For demonstration purposes, assuming you receive commands from a list
commands = ["on", "off", "toggle"] # Example list of commands
for command in commands:
print("Received command:", command)
# Process commands
if command == "on":
control_red_led(1)
elif command == "off":
control_red_led(0)
# Add more conditions as needed
# Wait before checking the next command
time.sleep(1) # Adjust the delay as needed
if __name__ == "__main__":
try:
while True:
# Check for TalkBack commands
process_talkback_commands()
# Determine the current state of the LED
led_state = RED_LED_PIN.value()
# Send LED state to ThingSpeak
send_data_to_thingspeak(led_state)
time.sleep(1) # Check for TalkBack commands every 5 seconds (adjust the interval as needed)
except KeyboardInterrupt:
pass
Loading
pi-pico-w
pi-pico-w