I've covered serial connections quite a lot recently, from micro:bit to laptop, Raspberry Pi, Adafruit Gemma M0. But each time I use my boiler plate serial listener code. It's clunky but it works. But for this Tooling Tuesday I've found something easy to use...
So what is it?
Microbitdongle is an easy to use and interesting module for Python that will connect to a micro:bit attached to your computer. No messing around with clunky code, rather we have a nice clean method to read and write data over a serial connection.
How can I install it?
Using the pip package manager for Python 3 we can install as so.
sudo pip3 install microbitdongle
Now what do I do?
Ok so the scenario is this, we have our micro:bit printing data to the REPL, and this is sent by default over a serial connection..handy!
To keep it simple we just use a infinite loop and keep printing "TEST", exciting I know, but easy to follow.
from microbit import * import time while True: print("TEST") time.sleep(2)
So this code is flashed to the micro:bit and connected to the computer. Now open a new file, in IDLE3 or in Mu (but change the mode to Python 3) and in the editor we shall write the following code to listen for a micro:bit serial connection.
Import the Dongle functionality from the module
from microbitdongle import Dongle
Create an object that will search and create the connection, by setting debug to True we will see connection information in the Python shell.
mb = Dongle(debug=True) # debug=False by default. Shows useful pairing information
Get the serial data and print it to the Python shell.
while True: data = mb.recv() print(data)
So running the code in the Python editor (IDLE / Mu) we will see the "TEST" text that we have sent from the micro:bit, via serial to the computer...handy!