Connect Pi Pico W in microPython with BLYNK

Make sure your’re using the latest lib: “1.0.0”

Then, try this in boot.py (I’m using a modified wifimanager to collect Blynk’s credentials but you can omit it and use a standard wlan connection:

from umachine import RTC, Pin, reset
import ntptime
import utime
from usys import platform, implementation
import gc
import wifimgr
gc.collect()

ESP32 = platform == 'esp32' or platform == 'esp32_LoBo'
RP2 = platform == 'rp2'
ESP8266 = platform == 'esp8266'

if ESP8266 or ESP32:
def ledfunc(pin):
    pin = pin
    def func(v):
        pin(not v)  # Active low on ESP8266
    return func
led = ledfunc(Pin(16, Pin.OUT, value = 0))  # LED for WiFi fail/not ready yet
if RP2:
def ledfunc(pin):
    pin = pin
    def func(v):
        pin(v)
    return func
wifi_led = lambda _ : None  # Only one LED
LED = 'LED' if 'Pico W' in implementation._machine else 25
green_led = ledfunc(Pin(LED, Pin.OUT, value = 1))  # Message received


def flash_led():
for x in range(5):
    green_led(False)
    utime.sleep(.25)
    green_led(True)
    utime.sleep(.5)


flash_led()     
        
def restart_and_reconnect(reason):
print('Some went wrong. Reconnecting...')
print('Due to ', reason)
utime.sleep(5)
reset()


try:
wlan = wifimgr.get_connection()
# wlan.disconnect()
if wlan is None:
    print("Could not initialize the network connection.")
    while True:
        pass  # you shall not pass :D
except Exception:
print('Connection error')
reset()


ssid = wifimgr.get_profiles()[0]
BLYNK_AUTH = wifimgr.get_profiles()[2]

# print("Network config:", wlan.ifconfig())

# sync time
utime.sleep(1)
try:
rtc = RTC()
ntptime.settime() # set the rtc datetime from the remote server
rtc.datetime()    # get the date and time in UTC
except Exception as e:
print(e)

def cetTime():
year = utime.localtime()[0]       #get current year
HHMarch   = utime.mktime((year,3 ,(31-(int(5*year/4+4))%7),1,0,0,0,0,0)) #Time of March change to CEST
HHOctober = utime.mktime((year,10,(31-(int(5*year/4+1))%7),1,0,0,0,0,0)) #Time of October change to CET
now=utime.time()
if now < HHMarch :               # we are before last sunday of march
    cet=utime.localtime(now+3600) # CET:  UTC+1H
elif now < HHOctober :           # we are before last sunday of october
    cet=utime.localtime(now+7200) # CEST: UTC+2H
else:                            # we are after last sunday of october
    cet=utime.localtime(now+3600) # CET:  UTC+1H
return(cet)

print(str(cetTime()[3]) + ':' + str(cetTime()[4]))
green_led(False)
gc.collect()

At boot, the above will display CET time (Madrid in my case). No need to use main.py to test the above code.

In main.py use:

import BlynkLib
from BlynkTimer import BlynkTimer

DEBUG = True
def dprint(*args):
        if DEBUG:
            print(*args)

dprint('Memory free', gc.mem_free())

VERSION = "1.0"
dprint('Code version: ', VERSION)
timer = BlynkTimer()

BLYNK_GREEN = "#23C48E"
BLYNK_BLUE = "#04C0F8"
BLYNK_YELLOW = "#ED9D00"
BLYNK_RED = "#D3435C"
BLYNK_DARK_BLUE = "#5F7CD8"

def R1_timeout(): green_led(False)

# Initialize Blynk
try:
#     blynk = BlynkLib.Blynk(BLYNK_AUTH) # faster
    
#      or....

    blynk = BlynkLib.Blynk(BLYNK_AUTH,
        insecure=True,          	# disable SSL/TLS
        server='lon1.blynk.cloud',	# lon1 fra1.blynk.cloud or blynk.cloud
        port=80,                	# set server port
        heartbeat=30, 				# set heartbeat to 30 secs      
        log=dprint              	# use print function for debug logging
        )
except OSError as e:
    dprint('ERROR', e)
    restart_and_reconnect(e)
    
    
@blynk.on("connected")
def blynk_connected(ping):
    dprint('Blynk ready. Ping:', ping, 'ms')
    blynk.sync_virtual()


@blynk.on("disconnected")
def blynk_disconnected():
    dprint('Blynk disconnected')
    utime.sleep(5)
    restart_and_reconnect('Blynk server failure...')
    
    
def check_wifi():
    gaugeColor = ''
    s = network.WLAN()
    e_ssid = ssid.encode('UTF8')
    try:
        rssi = [x[3] for x in s.scan() if x[0] == e_ssid][0]
        if (rssi > -99 and rssi < -80):
            newColor = BLYNK_RED
        elif (rssi <= -80 and rssi < -60):
            newColor = BLYNK_YELLOW
        else: newColor = BLYNK_GREEN
        
        if (newColor != gaugeColor):
            gaugeColor = newColor
            blynk.set_property(10, "color", gaugeColor)
        
        blynk.virtual_write(10, rssi)
    except IndexError as e:  # ssid not found.
        dprint('IndexError', e)
        rssi = -99
        

def uptime():
    blynk.virtual_write(0, utime.time()/10000)
    
    
@blynk.on("V1")
def blynk_handle(value):
    if int(value[0]) == 1:
        green_led(True)
        timer.set_timeout(1, R1_timeout)
    else: pass
    
   
def Loop():
    while True:
        gc.collect()
        blynk.run()
        timer.run()


# check on wifi every 15 seconds
timer.set_interval(15, check_wifi)
timer.set_interval(1, uptime) 

# Run blynk in the main thread
try:
#     import _thread
    Loop()
#     _thread.stack_size(5*1024)
#     _thread.start_new_thread(Loop, ())
except Exception as e:
    print(e)
    restart_and_reconnect(e)

You may need to change your Blynk local server. Mine is set to “lon1”. Pressing the V1 button on your app, the pico w’s LED should turn on/off. Beside that, you have a dbm gauge and an uptime display on your app. Just follow the code.