#############################################################################################
# Task 1 #2 : Button (Wokwi/hardware) turn on/off LED in Blynk.
# Switch (Blynk) turn on/off LED in Wokwi/hardware.
#############################################################################################
from machine import Pin
import time
import network
import BlynkLib
### Button's pin (real & virtual), LED's pin (real & virtual), WiFi and Blynk credentials
b_pin = 35
b_vir = 3
led_pin = 33
led_vir = 1
SSID = 'Wokwi-GUEST'
PASS = ''
TOKEN = 'E_4lvXx6QMQBXIxVmOzphQ5CQzcaYqfx'
### Connect to WiFi
wifi = network.WLAN(network.STA_IF)
if not wifi.isconnected():
print("Connecting to {}...".format(SSID))
wifi.active(True)
wifi.connect(SSID, PASS)
while not wifi.isconnected():
pass
print('Connected! IP:', wifi.ifconfig()[0])
### Initialize button, LED and Blynk
led = Pin(led_pin, Pin.OUT)
b = Pin(b_pin, Pin.IN, Pin.PULL_UP)
blynk = BlynkLib.Blynk(TOKEN, insecure=True)
@blynk.on("connected")
def blynk_connected(ping):
print('Blynk ready. Ping:', ping, 'ms')
blynk.virtual_write(b_vir, prev_b) # init Button/Label in Blynk
@blynk.on("disconnected")
def blynk_disconnected():
print('Blynk disconnected')
@blynk.on("V3") # Handler to process received data from V1
def v3_write_handler(value):
state = int(value[0]) # convert value to integer
if state == 1:
led.value(1) # Update LED
else:
led.value(0)
### get initial button's values
prev_b = b.value()
while True:
blynk.run()
curr_b = b.value() # get latest switch state
if curr_b == 0: # switch is pressed
led_val = 1 # value to turn on LED
else: # switch is released
led_val = 0 # value to turn off LED
#led.value(led_val)
if curr_b != prev_b: # if switch state changes
prev_b = curr_b
blynk.virtual_write(led_vir, led_val) # update LED in Blynk