Raspberry Pi Pico is C++ compatible.
Yes i know but the teacher told us to use microPython…
Here is my code :
import time
import network
from machine import Pin
import BlynkLib
led = Pin('LED', Pin.OUT) # to turn on the builtin LED
led.on()
ssid = '*****'
password = '*****'
BLYNK_AUTH = '**********'
"Connexion to WiFi"
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# Wait for connect or fail
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('waiting for connection...')
time.sleep(1)
# Handle connection error
if wlan.status() != 3:
raise RuntimeError('network connection failed')
else:
print('connected')
status = wlan.ifconfig()
print( 'ip = ' + status[0] )
"Connexion to Blynk"
# Initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH)
# Register virtual pin handler
@blynk.on("V0")
Led_red = Pin(28, Pin.OUT) #real pin on the Pi Pico
while True:
blynk.run()
I think it’s good for the network connection but i can’t do the code to turn on the led(Pin 28) if I press to the Button wich is on the virtual pin (V0).
This code is for Python but how transform it for µPython ?
void setup()
{
pinMode(2, OUTPUT); // Initialise digital pin 2 as an output pin
}
BLYNK_WRITE(V0) // Executes when the value of virtual pin 0 changes
{
if(param.asInt() == 1)
{
// execute this code if the switch widget is now ON
digitalWrite(2,HIGH); // Set digital pin 2 HIGH
{
else
{
// execute this code if the switch widget is now OFF
digitalWrite(2,LOW); // Set digital pin 2 LOW
}
}
Thank you so much for your help, we are close to the end !
Aurelien
It looks like C++ to me.
The answers are all in the library link I provided in post #2
The code will look something like this…
@blynk.on("V*")
def blynk_handle_vpins(pin, value):
print("V{} value: {}".format(pin, value))
Pete.
It’s a C++ code, not python coding.
Here’s an example
@blynk.on("V1")
def v1_write_handler(value):
if int(value) == 1:
GPIO.output(entradacaixa, 1)
else:
GPIO.output(entradacaixa, 0)
Thanks,
so in my case it’s like that ?
"Connexion to Blynk"
# Initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH)
# Register virtual pin handler
@blynk.on("V0")
def v0_write_handler(value):
if int(value)==1:
GPIO.output(Led_red, 1)
else:
GPIO.output(Led_red, 0)
while True:
blynk.run()
That’s right.
ok thanks but i didn’t understand why we use v0_write_handler(value). What’s the objective of this line of code ? Why write and no read ? We need to read the value of the virtual pin to send signal to the real one.
Thanks in advance
This handles data written from the Blynk server to the device, so in effect you are reading the data, but as the data output is instigated by the server when a virtual datastream value changes, it’s called a write handler in the sketch.
Pete.
Ok thank you so my code is good. If i push the button on blynk, it will turn my led on ?
The read function is a function that called when the device is requested to send its current value of the virtual pin to the server.
Setting the reading frequency was an option in the widget settings of the previous version of Blynk. I don’t believe it will function now because it’s not available in the new Blynk. You can give it a shot to see if it works or not.
A Blynk timer can be used to send data to the server at predetermined intervals.
Hi, I tested my code. I’m connected to Blynk but there is an error in the console. How solve this problem ? Thanks
connected
ip = 192.168.1.48
Connecting to blynk.cloud:443...
Traceback (most recent call last):
File "<stdin>", line 52, in <module>
File "/lib/BlynkLib.py", line 264, in run
File "/lib/BlynkLib.py", line 197, in process
File "/lib/BlynkLib.py", line 68, in emit
File "<stdin>", line 45, in v0_write_handler
TypeError: can't convert list to int
>>>
Here is my code
import time
import network
from machine import Pin
import BlynkLib
Led_red = Pin(28, Pin.OUT) #real pin on the Pi Pico
led = Pin('LED', Pin.OUT) # to turn on the builtin LED
led.on()
ssid = 'Proximus-Home-0DA0'
password = 'wsrbd3p369dzh'
BLYNK_AUTH = 'BO14B74EzwopkHmLr1jEhZAOCrSQnuhj'
"Connexion to WiFi"
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# Wait for connect or fail
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('waiting for connection...')
time.sleep(1)
# Handle connection error
if wlan.status() != 3:
raise RuntimeError('network connection failed')
else:
print('connected')
status = wlan.ifconfig()
print( 'ip = ' + status[0] )
"Connexion to Blynk"
# Initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH)
# Register virtual pin handler
@blynk.on("V0") #virtual pin V0
def v0_write_handler(value): #read the value
if int(value)==1:
GPIO.output(Led_red, 1) #turn the led on
else:
GPIO.output(Led_red, 0) #turn the led off
while True:
blynk.run()
you can’t convert an entire list into an integer. You should get an index from the list and convert that into an integer.
Should be
if int(value[0]) == 1:
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.