For an index to all my stories click this text.
As you might know I have several hobbies. electronics is one of them and bookbinding another.
For the decoration of a book I needed some ornaments. Bookbinding shops are hard to find. And I did not want to wait for one of the few bookbinding fairs in the Netherlands. So I decided to try to build some myself.
I am not a metalworker or woodworker but I do have a 3D printer. And I set out to make the ornaments with that.
Search ornaments on the web
I started by using Google to search for corner-ornaments. And that turned out well, I found many.
Copy the image with ctrl print-screen and paste it in your favorite
image editor. I use The Gimp for that: https://www.gimp.org/
Cut out the picture you want and save that to your harddisk.
Use convert.io to convert it to SVG
Import the svg into tinkercad and scale it to whish.
Mine was about 4 cm width and depth. I scaled the height to 1mm and then exported the STL.
Next I imported it in my slicer. For simple things like this I use the Creality slicer.
I sliced this at .3 mm.
That meant that it will have 3 layers and prints fast about 10 minutes for 2 pieces
Next step was printing them. I used white PLA as that is the easiest color to paint afterwards.
The printed ornaments were placed on an old newspaper and I sprayed them with gold and silver acrylic paint. I used a spraycan for this and of course did it outside.
And here is the result. I placed them on a book (pen for scale) with an artificial leather cover and they look quiete nice !!! At the time I did not glue them on as I was not yet shure which color would match best.
At closeup you can see the printing artefacts. But you will not notice them from a distance. Next time I'll try the ironingsetting in my slicer. For now this is good enough for me.
Till next time,
have fun
Luc Volders
Friday, July 18, 2025
3D Print your own book ornaments
Friday, July 11, 2025
Getting the right time: another method
For an index to all my stories click this text
Getting the right time is often a requirement for IOT and other projects.
Usually we use an NTP server for this like described in a previous story on this weblog which you can find here: http://lucstechblog.blogspot.com/2023/04/getting-right-time-with-micropython.html
There is just a small problem with this. If you have read that story you will know that you need to make a manual adjustment in the software for the Daylight Savings Time to get the right time. And that is annoying with a finished project. This means that you must update your program twice a year.
What if you want your program to automatically adjust to the right time ??
Well here is how to do that with MicroPython.
The pitfall.
There is no way to automatically get the right time if your finished project is regularly placed in another location, unless you are sure they are in the same timezone.
Your exact time is dependent on your geographic location. The local time in London is different from the time in Amsterdam for example.
So when your project is moved internationally an adjustment must be made for the location where it is at.
There is a trick for getting your location and we are going to use that here. However when the project moves from London to Amsterdam undoubtedly the microcontroller needs to contact another router for wifi access. And to achieve that you need to fill in the routers credentials. And there is your manual involvement.
Getting your location.
For getting the right time your program needs to know your location. And here is a nice trick for getting your location.
Your router is likely connected to a local internet provider. So you will get an internet IP address that is likely to be from your own timezone.
By connecting to the ip-api.com service you will get your internet IP address.
Let's try this first.
Just point your browser to https://ip-api.com/
scroll a bit down and there is your information.
I camouflaged my own IP number as I want some privacy.
But look at the info and you can see that IP-API.COM estimates that my IP number originates from the town Boekel in the Netherlands.
Well actually that is not my location but the important part is that this is in the same Time-Zone as I am. So using my Internet IP number indeed points to the right timezone.
When you move your project to a different location you only have to point your browser to https://ip-api.com/ to know if your program will automatically get the right timezone. If that is so you do not need to make any changes to your program.
We will need the IP address in the next step which is getting the right time. But to achieve that we first need our program to fetch the IP address from the ip-api.com website.
Using the Internet IP address to get the right time
Now let's have a look at the ip-api.com documents page: https://ip-api.com/docs
Above shows the part from the documentaion that tells how to use the api to get the response in JSON code.
http://ip-api.com/json
So this is the only part we need to translate into MicroPython. And here it is.
import network import urequests # Router credentials ssid = "YOUR-ROUTERS-NAME" pw = "YOUR PASSWORD" print("Connecting to wifi...") # wifi connection wifi = network.WLAN(network.STA_IF) # station mode wifi.active(True) wifi.connect(ssid, pw) # wait for connection while not wifi.isconnected(): pass def get_public_ip_address(): response = urequests.get('http://ip-api.com/json') json_data = response.json() return json_data['query'] ip_address = get_public_ip_address() print(ip_address)
Running this program will put the Internet IP-address into the variable ip_address and prints it out in Thonny's shell.
I dont think this needs any explanation. The received data is JSON code and we distill the information from the line "query" from that and that presents us the IP address.
If you need more information on how to program in MicroPython and how to use the requests library or to distill JSON information I can recommend my book: Raspberry Pico W simplified. These things are discussed in details in the book.
You can buy it from Amazon. Click here or the above picture for the link.
Using the IP-Address to get the right time.
Now we have our Internet IP-Address we can use that to get the right time for our time-zone. We are going to use the https://timeapi.io/ service for that.
https://timeapi.io/ is a free service that will provide us the right time for our location. To do so we use their API call and provide our Internet IP-address. You can find all documentation on this site: https://timeapi.io/swagger/index.html
As you can see there are a lot of possibilities. We can use our IP address to get the right time and we can also use our latitude and longitude if they are known. Let's stick to getting the time by using the just found IP address.
The page offers you the possibility to try it out. And if you do you will get an example on how to code the API and the results are displayed further on. We are interested in how the API call should be used and the page shows how it is done:
https://timeapi.io/api/Time/current/ip?ipAddress=237.71.232.203
The provided internet IP=address is just a sample. We will have to replace that with our own IP address.
This is how that is done:
response = urequests.get('https://timeapi.io/api/Time/current/ip?ipAddress='+ip_address) json_data = response.json() print("Hour : "+str(json_data["hour"])) print("Time : "+str(json_data["minute"]))
The urequests library calls the API and in the call we added our own just found IP-address.

And here is the information shown in Thonny's shell. And believe me the time was accurate.
The complete code.
For your convenience I hereby give you the complete program
import network import urequests # Router credentials ssid = "YOUR-ROUTERS-NAME" pw = "YOUR-PASSWORD" print("Connecting to wifi...") # wifi connection wifi = network.WLAN(network.STA_IF) wifi.active(True) wifi.connect(ssid, pw) # wait for connection while not wifi.isconnected(): pass def get_public_ip_address(): response = urequests.get('http://ip-api.com/json') json_data = response.json() return json_data['query'] ip_address = get_public_ip_address() print(ip_address) response = urequests.get('https://timeapi.io/api/Time/current/ip?ipAddress='+ip_address) json_data = response.json() print("Hour : "+str(json_data["hour"])) print("Time : "+str(json_data["minute"]))
Power Failure
I am sure you will notice that this is a great way to get the accurate time for your IOT and other projects. Get the significant part of this program and use it in your own project so you will automatically get the right time even after a power failure.
Till next time
Have fun
Luc Volders
Friday, July 4, 2025
MicroPython bytecode speed test
For an index to all my stories click this text
In the previous story I wrote how you can make your MicroPython sourcecode unreadable for most users. I did that for trying to protect my program. The way to do this is to convert your program into bytecode. You can read that story here:
https://lucstechblog.blogspot.com/2025/06/protect-your-micropython-sourcecode.html
After I published that story here on my weblog I received a mail from a reader that asked if the bytecode was actually faster as standard MicroPython. The question is valid as bytecode is actually easier to interpret as MicroPython code.
So I did some tests.
Prime numbers
I took a smal program that calculated and printed a few thousand prime numbers. Here is the code.
import time start_time = time.ticks_ms() def is_prime(n): if n < 2: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True count = 0 n = 2 while count < 5000: if is_prime(n): print(n) count += 1 n += 1 end_time = time.ticks_ms() elapsed_time = time.ticks_diff(end_time, start_time) print("Elapsed time:", elapsed_time, "milliseconds")
This code took 32993 miliseconds to run on an ESP8266 with MicroPython V1.20.1.
Then I converted the program to bytecode and it took 32149 microseconds to run. So it was 844 miliseconds (almost a full second) faster.
That is 2.5% faster.
So it is a bit faster but not a lot to gain..
Without print
A lot of time is consumed by the print statement. Print is dependend on the serial communication between the microcontroller and your computer. So let's see what we gain if we leave the print command out.
import time start_time = time.ticks_ms() def is_prime(n): if n < 2: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True count = 0 n = 2 while count < 5000: if is_prime(n): count += 1 n += 1 end_time = time.ticks_ms() elapsed_time = time.ticks_diff(end_time, start_time) print("Elapsed time:", elapsed_time, "milliseconds")
It's the same program without the print command in the while loop.
The program now took 32385 miliseconds to run.
Again I converted it to bytecode and then it needed 31570 miliseconds to run.
That is 815 miliseconds faster. Again almost a second faster.
And that makes it also 2.5% faster.
This is just a small test but this already shows that bytecode is a bit faster as MicroPython code. So you might gain some speed in certain projects.
Conclusion
Byte code is not real native machine language but an in-between step. This small test already shows that bytecode is a bit faster as MicroPython code. So you might gain some speed in certain projects.
This is not a scientific test just a small
test to see if there is any speed to gain. Your results might vary
depending on the Microcontroller you are using (ESP8266, ESP32,
Raspberry Pi pico etc.) size of the program, libraries used and commands
used. So make some tests for yourself.
Till next time,
have fun
Luc Volders
Friday, June 27, 2025
Protect your MicroPython sourcecode
For an index to all my stories click this text
I am/was working on a large project. The project consisted of a microcontroller with some sensors. That microcontroller sends it's data to a dedicated app on an Android phone. Both the microcontroller and the app have to do some complicated calculations.
As I want to show the prototype to several people who might be commercially interested I don't want them to have the opportunity to peek at my software.
I am a lazy developer. So to speed up things I wrote the software for the microcontroller in MicroPython. It works flawless but is not hidden for anyone who connects a computer to the microcontroller. So I had to find a way to hide the program. At least to make it unreadable.
Sidenote.
When you write the programs for your microcontroller with the Arduino IDE it is almost impossible for someone to get the code out of the controller to examine it. Next to that the C++ code you wrote is compiled into machine language by the IDE which is unreadable for most. These two properties keeps your code quite safe. So maybe (when there is time) I will rewrite the program in Arduino language.
How MicroPython works.
MicroPython is an interpreted language. So you write your program in MicroPython and send it to the microcontroller. The code is stored on the microcontroller before it runs. The microcontroller has the MicroPython interpreter on board that converts the code into something the microcontroller understands. So your sourcecode is stored on the Microcontroller ready for anyone to retrieve.
An interpreted language like MicroPython is, is therefore significant slower as the machine language the Arduino IDE produces.
The MicroPython developers found a solution to speed things up.
The MicroPython program is first converted into bytecode. The step between bytecode and machinelanguage is easier and therefore your program will run faster. Still not as fast as pure machinecode, but a lot faster as full MicroPython.
The solution
Bytecode is unreadable by us mere humans. And that offers opportunities for obfuscating the source code.
Here is a simple MicroPython program:
I just wrote this in Thonny and saved it to my computers harddisk.
And this is how the bytecode looks.
I am sure that most people that would get this code in their hands would not have a clue on how to alter this or examine it.
So what we need is a program that takes our MicroPython source code and compiles it into bytecode. And lucky for us this software exists.
Download mpy-cross
The program we need is called mpy-cross and you can get it here:
https://gitlab.com/alelec/mpy_cross/-/packages/7514584
As you can see I used this first when I still was running Windows. You might know that I switched to Linux as my operating system. There is a version of mpy-cross for Linux to and I will discuss how to use that in a future article.
At the time of this writing version V1.20.0 was the latest version. Always check for the latest version and use that.
Click on the latest version and a new window opens.
Scroll down on that page till you find the version for your computer. Mine is:
mpy-cross-v1.20.0-win_x86_64.exe
Download it and install it on your computer in a dedicate directory.
Your computer might give a warning that the software might be unsafe. I tested the package with my virus scanner before installing it and it was totally safe.
My version downloaded and had the name: mpy-cross-v1.20.0-win_x86_64
I altered the name in just mpy-cross
Using mpy-cross
Start with copying your MicroPython program into the directory where the mpy-cross program is.
The program mpy-cross needs to be started from the command line. Just double clicking it will not work.
To achieve this here is a nice trick.
Click on the yellow icon in front of the path to the directory where the mpy-cross program and your python code is.
Now type cmd
And the commandline window opens with the prompt at the right directory.
In my directory there were only two files: mpy-cross and test01.py
And the test01.py file is the file I wanted to compile.
Use the command
mpy-cross test01.py
Just replace the name test01.py with the name your MicroPython source code has.
Press enter and after a (short) while the prompt returns. The time it takes to compile your code depends on the complexity and size of your sourcecode.
And there is the bytecode file. It has the name test01 and looks like a text file but as you have seen in the second picture in this article it is nothing like a text file.
How to use the bytecode file
The file test01.mpy is uploaded to Thonny. Clicking on the name of the file produces an error. MicroPython does not seem to recognise the program code.
This is what you need to do:
Make a program containing just a single line:
import test01
That's all. It will load the file test01 and run it. You can see the result in Thonny's shell.
It does not need to be a program with a single line. The test01.mpy code can be part of a larger program. You just treat it like it is a library.
Concluding
This will not stop people from copying the bootcode file from your MicroPython device. But it will prevent most to analyse your program.
Please be aware that a bytcode file can not be used as main.py to automatically run your program at start-up. So make a one-line file (as discussed above) as your main.py file that calls the bytecode file.
Till next time
have fun
Luc Volders
Friday, May 23, 2025
Ubuntu problem with ESP8266 and Thonny solved
As you might know I have migrated from Windows to Linux. My computer is getting old and slow. Slow is mostly due to running Windows as Windows constantly does all kinds of tasks in the background. Linux does not have that problem and is therefore a lot faster.
There are many flavors of Linux and I am running Kubuntu 24.04. LTS stands for Long Time Service meaning it is supported until june 2027.
So far so good. All the standard programs work as expected. But then I ran into a problem.
MicroPython on Kubuntu
I am using Thonny as my standard editor for MicroPython programs and that works as a charm. I connected the Raspberry Pi Pico, Pico W and ESP32 without a problem.
Only the ESP8266 (Wemos D1 Mini) would not work. Although it worked previously on my Windows setup.
It was not recognised in Thonny.

The above screendump shows that I chose the ESP8266 in the tools menu.

Nevertheless I got this error. And also several other errors.
So I started an internet search.
I found that Kubuntu installs standard a utility that is called BRLTTY This is a service that provides access to the console for a blind person using a refreshable braille display.
Fortunately I am not blind and I do not need this service. So I could delete it without consequences.
sudo apt purge brltty -y
This the command to remove brltty from Ubuntu permanently. Copy it and paste it in your Terminal program. Use sudo as you need Super User privileges to remove and install software. Linux will ask you for the administrator password.
sudo usermod -a -G dialout $USER
Then use this command to get full access to the USB port
And here is the result:

The ESP8266 comes up in the list with available Python versions.

Problem solved !
Till next time
Have fun.
Luc Volders
Friday, May 16, 2025
Overclocking the Raspberry Pi Pico in MicroPython
For an index to all my stories click this text
This story is about overclocking (and underclocking) the Raspberry Pi Pico with MicroPython.
Sometimes you just want your program to run faster. Well you can gain speed by using C++ (Arduino language) in stead of MicroPython. But not everybody wants that as MicroPython is far easier to learn and use.
MicroPython runs on the ESP8266, ESP32 and of course on the Raspberry Pi Pico. And if you use the Picom or Pico W, you are in luck: the Pico can be overclocked !!! And without altering anything or adding extra hardware !! The internal clock can be software wise altered !!
Overclocking
Overclocking means that you can alter the speed on which your microcontroller (or computer) works.
The documentation of the Raspberry Pi pico says that it runs normally on 133Mhz but the speed can be increased to 400Mhz.
There are two things to consider:
- The onboard SPI flash memory may give trouble when working above 260Mhz
- Overclocking might shorten the lifespan of the Pico
For most projects the Pico just runs fine. But there might be some time critical programs in which you could need a bit more speed. The lifespan shortening sounds troublesome, but until now I have not heard or read on the internet anyone who had a Pico giving up due to overclocking. Just be warned.
Overclocking in MicroPython
Overclocking is standard facilitated in MicroPython. You do not need to download extra libraries. You just need the machine library which is standard included in MicroPython.
So let's first start by examining the standard frequency. We just need two commands for that which you can put in Thonny's shell.
import machine
machine.freq()
And there it is. Standard sets MicroPython the clock-frequency to 125.000.000 which is 125Mhz. That is a bit lower as the 133Mhz the Raspberry documentation states.
Test program
Let's buid a small test program so we can see if overclocking has any effect at all.
import time start = time.ticks_ms() print("Micropython tips") for x in range(1000000): x=x end = time.ticks_ms() print(end - start)
The program does nothing special. It puts the start time into a variable, then puts 1 million times the value of variable x into itself and then stores the end time. Lastly startime is subtracted from endtime and then we know how long it took.

And here is the result. our small program took about 8 and a half second to finish.
Now let us increase the clockspeed.

The command to alter the clock frequency is machine.freq(x) in which x is the frequency you need. I set the speed at 260000000 which is 260Mhz. Then I ran the program again.

And what an increase in speed !!! The program now just took 4 seconds.

The highest speed I could get was 285000000 Hz which is 285Mhz. Any higher speeds would block the communication between Thonny and the Pico. Like stated before, increasing the speed might affect your interfaces with I2C, SPI and UART. And here it shows that above 285 Mhz it definitely affects the UART communication.

At 285Mhz the program just needed a bit less than 4 seconds.
You could test if anything beyond 285Mhz might work as no Pico's is created 100% equal and you might get lucky.
I recommend not to go over 260Mhz.
Lowering the speed.
Next to increasing the speed you can also decrease the speed. Lowering the speed at which a program runs might prove usefull in debugging.

The lowest I could go was 20000000 Hz which is 20Mhz. Any lower and I lost contact with Thonny.

At 20Mhz the program took almost 53 seconds to finish.
Please test thorough !!!
Increasing the speed to the max or decreasing the speed to the minimum might influence communications with sensors and actuators working with I2C or SPI. It also may influece communication over the UART ports.
So if you need to permanently increase the speed for one of your projects please test thorough before putting it in a real life situation.
Till next time
Have fun
Luc Volders
Friday, May 9, 2025
Raspberry Pi pico with Bluetooth
Some time ago I published a story on how to have the ESP32 communicate over bluetooth with your android Phone. Normally we use Wifi to communicate with the ESP32 but there might be circumstances in which you do not want that or can not use Wifi. You can re-read that story here: https://lucstechblog.blogspot.com/2024/08/esp32-bluetooth-classic-part-2.html
As you might know I wrote a book on the Raspberry Pi Pico which is a great microcontroller made by the Raspberry Pi Foundation. The Pico is not a linux computer but a Microcontroller like the Arduino's or ESP series. It has excellent features and a really good price-tag. A Pico can be had locally for around 5USD. One of the readers of my book who is also a follower of this blog asked if it was possible for the Raspberry Pi Pico to communicate with his phone.
Well that is not directly possible as the Raspberry Pi Pico has no communication means on board. There is standard no Wifi or Bluetooth like the ESP8266 or ESP32 have.
There is however a solution available.
Back in 2016 as faithfull readers of this blog might remember I wrote a story on how to attach an ultrasonic distance meter to an Attiny85 and send it's data to a phone using a HC-06 bluetooth module. These modules are cheap and easy to get.
We can use that same module and attach it to a Raspberry Pi Pico to send data to your phone or receive data and commands from your phone. And that is exactly what we are going to do. You can use a HC-05 or HC-06 for this. Just use that what is most easily available.
The story written in 2016 about the Attiny 85 used C++ (Arduino language). For the Raspberry Pi Pico I am going to write a program in MicroPython.
The Phone App is written in MIT's App Inventor. You can find App Inventor here: https://appinventor.mit.edu/
App Inventor has been featured in several stories and tutorials on this weblog which you can find here: http://lucstechblog.blogspot.com/p/index-of-my-stories.html
Bluetooth communication.
The Pico has so called UART connections. An UART is a, in this case build-in, hardware module that converts the data into a serial stream. The Pico has two UART's build in UART0 and UART1. I am using UART0 in this case.
To have the Pico communicate over bluetooth we need to attach a Bluetooth adapter that can convert the electrical signals from the Pico into a wireless transmission. The module often used for that is the HC-05 or the HC-06. So the HC-06 is connected to the internal UART. The breadboard setup shows how it is done.
The hardware setup

The Raspberry Pi Pico has ample I/O pins so for this test I am using 2 I/O pins for the communication with the HC-06 bluetooth module, and I use 4 I/O pins to attach leds.

The HC-06 is attached to the GND (pin 38) and 3V3-OUT (pin 36) for getting it's power. The TX line of the HC-06 is attached to the RX line (pin 2) of the Pico. The RX line of the HC-06 is attached to the TX line (pin 1) of the Raspberry Pi Pico. So the RX and TX lines are crossed. This makes sense. The Pico sends (TX) data to the Bluetooth module that receives that data (RX) and the other way round.
Next the 4 leds are connected to GND using a current delimiting resistor of 220Ohm and connected to the Pico's pins 15, 16, 17 and 19 which are GPIO 14, 13, 12 and 11.
Last year I made a Raspberry Pi Pico pin layout which you can print and lay on top of the Raspberry Pi Pico for easy reference. You can find that here: http://lucstechblog.blogspot.com/2021/03/raspberry-pico-pin-layout-help.html
The App
To have your Pico and Phone talk to eachother you need an App on your phone. The App I am going to show how to develop is for an Android Phone. As App Inventor nowadays also can be used to develop Apple app's you could adapt the program for an Iphone. However you're on your own here as I do not own an IPhone and am not willing to buy one due to it being terribly overpriced.
Unfortunately I do not have the space and time here to give you a complete App Inventor course. App Inventor does not have a steep learning curve and spending some hours with the program should get you going. Next to that there are several tutorials and examples on this weblog and App Inventor itself offers several tutorials. Check those here http://lucstechblog.blogspot.com/p/index-of-my-stories.html and here: https://appinventor.mit.edu/

This is how the screen will look eventually. At the top there is a ListPicker used for picking the right Bluetooth device. Below that there is a Tablearrangement. Inside the TableArrangement I placed 8 buttons that send commands for setting the led on or off.
Below that you see an empty square. That is a label (Label2) in which texts received from the Raspberry Pi pico will be shown.
And below that Label is Label1 with a ridiculous copyright notice.
Arrange the items to your own linking and give them the looks and colors of your choice. Play with this to learn how to use App Inventor and it's possibilities and functions.
There are 3 non-visible components at the bottom of the designer screen. The first one is the BluetoothClient component, the second is the Notifier component and the last is the clock component. You can find these in the menu on the left side of the designer screen (not shown here).
Drag them into the phone simulation screen and they will be placed at the bottom like shown here.
Now switch over to the blocks section.
-p.png)
This is a picture of all the necesary blocks. It may look complicated but if you get the hang of it, it really isn't.

Start with a Listpicker and put all the names and Bluetooth adresses in the list.
When the ListPicker has all the Bluetooth data and the user presses (clicks) on the desired Bluetooth device connect to it. When connected set a message on the screen (with the notifier) that the connection has succeeded or failed.

Create a block for each button that sends a particular text over Bluetooth when the button is clicked.

Here you can see the blocks that are used to set the first led on or off. When Button1 is clicked first the Bluetooth connection is tested. No use to try to send a command over Bluetooth when the device is not connected...
Then we send on1# if Button1 is pressed or off1# when Button2 is pressed.
The # is attached to the text as a means for the Pico's Python program to detect if receiving the message is completed.
The blocks for Button3 to Button8 are identical and only differ in the message they are going to send.
This last block uses the clock function to check every second wether there is a message received over Bluetooth. If a message is received it is displayed in Label2.
And that completes the App for your phone.
If you do not want to compose all the blocks yourself I have a copy of the above code available for you to download here:
https://www.mediafire.com/file/554kyre473onlh0/Pico_bluet_SR.aia/file
The Python program for the Pico.
Now we have a complete app available that can send and receive data over Bluetooth let's look at the Pico side. Here is the complete MicroPython program.
import os
import utime
from machine import UART, Pin
#print sys info
print(os.uname())
L1 = Pin(14,Pin.OUT)
L2 = Pin(13,Pin.OUT)
L3 = Pin(12,Pin.OUT)
L4 = Pin(11,Pin.OUT)
#indicate program started visually
led_onboard = machine.Pin(25, machine.Pin.OUT)
led_onboard.value(1) # onboard LED ON for 0.5 sec
utime.sleep(0.5)
led_onboard.value(0) # onboard LED ON for 0.5 sec
uart = machine.UART(0, baudrate=9600,
bits=8, parity=None, stop=1)
print(uart)
uart.write("hello")
utime.sleep(1)
uart.write("The temperature is : ")
uart.write(str(35))
L1.value(1)
utime.sleep(1)
L1.value(0)
L2.value(1)
utime.sleep(1)
L2.value(0)
L3.value(1)
utime.sleep(1)
L3.value(0)
L4.value(1)
utime.sleep(1)
L4.value(0)
while True:
b=""
a=""
c=""
while a != "#" :
a = uart.read(1)
c = (a.decode('utf-8'))
a = c
if (c != "#"):
b = b + c
print("received chars: ",len(b)," = ",b)
if "on1" in b:
L1.value(1)
uart.write("Led 1 On")
if "off1" in b:
L1.value(0)
uart.write("Led 1 Off")
if "on2" in b:
L2.value(1)
uart.write("Led 2 On")
if "off2" in b:
L2.value(0)
uart.write("Led 2 Off")
if "on3" in b:
L3.value(1)
uart.write("Led 3 On")
if "off3" in b:
L3.value(0)
uart.write("Led 3 Off")
if "on4" in b:
L4.value(1)
uart.write("Led 4 On")
if "off4" in b:
L4.value(0)
uart.write("Led 4 Off")
As usual I will show how this program works by highlighting certain parts.
import os
import utime
from machine import UART, Pin
First we import all the necesary libraries.
L1 = Pin(14,Pin.OUT) L2 = Pin(13,Pin.OUT) L3 = Pin(12,Pin.OUT) L4 = Pin(11,Pin.OUT)
The four led's are defined and the I/O pins where they are attached to are set as OUTput.
#indicate program started visually led_onboard = machine.Pin(25, machine.Pin.OUT) led_onboard.value(1) # onboard LED ON for 0.5 sec utime.sleep(0.5) led_onboard.value(0) # onboard LED ON for 0.5 sec
Then we blink the Pico's internal led as an indication that the program has started.
uart = machine.UART(0, baudrate=9600, bits=8, parity=None, stop=1) print(uart)
These lines define the serial communication's settings and display them in Thonny's shell when the program runs.
uart.write("hello")
utime.sleep(1)
uart.write("The temperature is : ")
uart.write(str(35))
This is a test in which we send a fake message to the phone. First the word "hello"is send and next "The temperature is 35" As you can see the last line converts the number 35 into a string that can be send over Bluetooth.
L1.value(1)
utime.sleep(1)
L1.value(0)
L2.value(1)
utime.sleep(1)
L2.value(0)
L3.value(1)
utime.sleep(1)
L3.value(0)
L4.value(1)
utime.sleep(1)
L4.value(0)
The leds are all set on and then off as a test so we can see they are working and attached to the right I/O pins.
Then comes the most important part of the program. It is where an incoming message from the Phone is read and decoded.
while True:
b=""
a=""
c=""
while a != "#" :
a = uart.read(1)
c = (a.decode('utf-8'))
The program starts with defining some helper variables and making them empty.
Next a test is done wether the variable a comntains "#" if that is the case it is the last character received and it should be ignored.
If it is not "#" the next character is read from the uart and decoded to a normal ascii value.
a = c if (c != "#"): b = b + c print("received chars: ",len(b)," = ",b)
Again we test wether the received character is "#" and if not the character is added to the variable b. Then we print in the shell the received characters and the length of the total received characters. This is just a test to see if everything send from the phone is indeed received.
if "on1" in b: L1.value(1) uart.write("Led 1 On") if "off1" in b: L1.value(0) uart.write("Led 1 Off")
When "#" is received the command is now complete and stored in the variable b. Now we can test which command is received and set the appropriate led on or off.
Then we send "Led 1 On" or "Led 1 Off" back to the phone so the phone can check if the command really has been received and the command is executed.
These lines are repeated for all 4 leds.
In the field
When te App is started firrst press on the field with the text "Pick your Bluetooth device" and make sure Bluetooth is activated on your phone.
A new screen opens showing all Bluetooth devices available and the ones that you have used in the past. The top one has the Bluetooth adress and name (HC-06) we want to connect to. Press on that line and the connection is made.
Now you can use the app and switch the led's on and off.
This clearly demonstrates how to receive data from Bluetooth and how to send data over Bluetooth.
Of course this is just a framework to send and receive all kinds of data from your phone to the Raspberry Pico and the other way round.
For more detailed info on the Raspberry Pi Pico, a short course on MicroPython and using all kinds of sensors with the Pico please buy my book Raspberry Pi Pico Simplified: https://lucstechblog.blogspot.com/2021/08/raspberry-pi-pico-simplified-now.html
Till next time
have fun
Luc Volders