# from machine import Pin
# from time import sleep
# # ESP32 GPIO 26
# relay = Pin(5, Pin.OUT)
# while True:
# # RELAY ON
# relay.value(1)
# sleep(5) # should be greater than 2 sec
# # RELAY OFF
# relay.value(0)
# sleep(5) # should be greater than 2 sec
import time
import urequests as requests
import network
import machine
# Define RGB LED cathode pins
red = machine.Pin(5, machine.Pin.OUT)
def do_connect():
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect("Wokwi-GUEST", "")
while not sta_if.isconnected():
pass
print('network config:', sta_if.ifconfig())
do_connect()
# Function to set the color of the common anode RGB LED
def ledON():
red.on()
def ledOFF():
red.off()
def get_button_state():
response = requests.get('http://sajidmajeed.pythonanywhere.com//api/get-led-state')
data = response.json()
return data
# Initialize the previous state to an initial value
prev_button_state = {"state": None}
while True:
try:
button_state = get_button_state()
if button_state != prev_button_state:
print(f'Button state: {button_state}')
prev_button_state = button_state
index = prev_button_state['led_state']
print(type(index))
if index == 0:
ledON()
else:
ledOFF()
time.sleep(1) # Check the state every 1 second
except KeyboardInterrupt:
break
# Disconnect from Wi-Fi when done
network.WLAN(network.STA_IF).disconnect()