BBC micro:bit
Serial Port Connection
Introduction
This section is about how to use Visual Basic to read data that you write to the USB connection using MicroPython. You need to be working on a PC that has the correct serial port driver installed. You can download the driver from here.
On this page, we'll start by making a small program that can connect to the micro:bit and read any data that we send to the serial port from our micro:bit programs.
To write the program, I used Visual Basic 2015 in the Visual Studio 2015 Community Edition. This is free to download and use. Other versions are likely to work the same for this program.
Visual Basic Program - Form Design
First you need to create a new project. Choose to make a Visual Basic Windows Application and give the project a suitable name before pressing the create button.
Design your form using the tools in the toolbox. When an object is selected, the Properties Window will allow you to change its properties. The form will need to look like this,
This is not as tricky as it might look. Click on components in the tool box and then draw them onto the form. Follow these instructions for the object names and properties and the code will work properly for you.
Item | Name | Properties |
---|---|---|
Label | Label1 | Text: Port |
Combo Box | cmbPort | |
Button | btnConnect | Text: Connect |
Button | btnDisonnect | Text: Disconnect |
Button | btnClear | Text: Clear |
TextBox | txtOuput | Multiline:True Scrollbars: Both |
StatusStrip | StatusStrip1 |
Click on the button on the StatusStrip and add a StatusLabel. Name it tsConnection.
Visual Basic - Programming
Now we are ready to write some code.
At the very top of the code window, you will need to import the references to the serial port. You do this with the following line,
Imports System.IO.Ports
You will also need a global variable to represent the serial port we connect to. You do this with the following statement,
Dim WithEvents sp As New SerialPort
The next set of statements define a few procedures we need to use. First you have a subroutine to list the serial ports that are available. Depending on the peripherals you have attached to the PC, this could be a few. There is also a procedure to add text to the end of the text box.
Private Sub GetSerialPortNames()
For Each sport As String In My.Computer.Ports.SerialPortNames
cmbPort.Items.Add(sport)
Next
End Sub
Sub ShowString(ByVal myString As String)
txtOutput.AppendText(myString)
End Sub
Delegate Sub myMethodDelegate(ByVal [text] As String)
Dim myDelegate As New myMethodDelegate(AddressOf ShowString)
Double click on an empty part of the form and the code window should pop up with headers for the Form_Load event. The following code will populate the ComboBoxes.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Try
GetSerialPortNames()
cmbPort.SelectedIndex = 0
Catch
MsgBox("No ports connected.")
End Try
End Sub
Connecting
Double click on the Connect button to bring up the headers for its click event. The following code is used to make the connection to the port,
Private Sub btnConnect_Click(sender As System.Object, e As System.EventArgs) Handles btnConnect.Click
Try
sp.BaudRate = 115200
sp.PortName = cmbPort.SelectedItem.ToString
sp.Parity = Parity.None
sp.DataBits = 8
sp.StopBits = 1
sp.Open()
If sp.IsOpen Then
btnConnect.Visible = False
cmbPort.Enabled = False
tsConnection.Text = "Connected on " & sp.PortName
btnDisconnect.Visible = True
End If
Catch
sp.Close()
End Try
End Sub
Disconnecting
Double click on the Disconnect button to bring up the headers for its click event. The following code closes the connect to the port,
Private Sub btnDisconnect_Click(sender As System.Object, e As System.EventArgs) Handles btnDisconnect.Click
Try
sp.Close()
btnConnect.Visible = True
btnDisconnect.Visible = False
cmbPort.Enabled = True
tsConnection.Text = "Not connected"
Exit Sub
Catch
MessageBox.Show("Some kind of problem.")
End Try
End Sub
We also need to make sure that a disconnection is made before the program is closed. Go to the properties window for the form. Click on the lightning symbol to find the list of events. Double click in the box next to Form_Closing and add the following code,
Private Sub Form1_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
If sp.IsOpen() Then
MessageBox.Show("Disconnect before closing")
e.Cancel = True
End If
End Sub
This last block of code prevents the user from closing the form without first disconnecting.
Clearing
Double click the Clear button and add the following code to allow you to clear the text box.
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtOutput.Text = ""
End Sub
Receiving Data
Our last main job is to create an event handler to process information arriving at the serial port.
Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles sp.DataReceived
Dim str As String = sp.ReadExisting()
Invoke(myDelegate, str)
End Sub
MicroPython - Testing The Connection
Here is a simple program to test the connection for us. Flash it to the micro:bit.
from microbit import * while True: if button_a.is_pressed(): print("BUTTON A PRESSED") sleep(200) elif button_b.is_pressed(): print("BUTTON B PRESSED") sleep(200) sleep(50)
With the micro:bit still connected via USB, run the Visual Basic program. Select the correct port (usually the higher number) and click on the connect button. Pressing buttons A and B should result in something like this,
Generating Text
You can copy text from the large text box using keyboard shortcuts or you can add some more functionality to the Visual Basic program to do it more quickly. Let's write a few MicroPython programs to generate text for us,
The following program outputs a list of binary numbers if you press the A button and hexadecimal numbers if you press the B button.
from microbit import * def OutputBinary(): for i in range(0,256): print(str(i) + ": " + '{:08b}'.format(i)) return def OutputHex(): for i in range(0,256): print(str(i) + ": " + '{:02x}'.format(i)) return while True: if button_a.is_pressed(): OutputBinary() sleep(1000) elif button_b.is_pressed(): OutputHex() sleep(1000) sleep(50)
Challenges
You don't need to do any more work on the Visual Basic program to get some use out of this. Concentrate on the MicroPython and what you can do with that first.
You can generate times tables and sequences of numbers (triangular numbers, square numbers, Fibonacci numbers.
Test out all of the built-in components and send readings to the USB port.