In this example we will create a VB.net program that will read data from the serial port, in this case a Microbit connected to the PC. We will then upload a program to our microbit that sends data via the serial port when a button is pressed.
This is a picture of the app will be creating, as you can see it has a combo box with available comms ports listed, connect and disconnect buttons and a textbox which will display serial data from the microbit. You can see the app running and the results of some key presses
Microbit Code
This was written in python using the Mu editor
[codesyntax lang=”python”]
from microbit import * while True: if button_a.is_pressed(): print("Button A was pressed") sleep(250) elif button_b.is_pressed(): print("Button B was pressed") sleep(250) sleep(100)
[/codesyntax]
Application Code
[codesyntax lang=”vbnet”]
Imports System.IO.Ports Public Class frmMicroBit Dim WithEvents serialPort As New SerialPort Delegate Sub myMethodDelegate(ByValAs String)
Dim myDelegate As New myMethodDelegate(AddressOf DisplaySerialText)Private Sub GetSerialPortNames()
For Each sport As String In My.Computer.Ports.SerialPortNames
cboPorts.Items.Add(sport)
Next
End SubPrivate Sub frmMicroBit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
GetSerialPortNames()
cboPorts.SelectedIndex = 0
Catch
MsgBox("No ports connected.")
End Try
End SubPrivate Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
Try
serialPort.BaudRate = 115200
serialPort.PortName = cboPorts.SelectedItem.ToString
serialPort.Parity = Parity.None
serialPort.DataBits = 8
serialPort.StopBits = 1
serialPort.Open()
If serialPort.IsOpen Then
btnConnect.Visible = False
cboPorts.Enabled = False
btnDisconnect.Visible = True
End If
Catch
serialPort.Close()
End Try
End SubPrivate Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
Try
serialPort.Close()
btnConnect.Visible = True
btnDisconnect.Visible = False
cboPorts.Enabled = True
Exit Sub
Catch
MessageBox.Show("Problem closing port")
End Try
End SubSub DisplaySerialText(ByVal myString As String)
txtSerial.AppendText(myString)
End SubPrivate Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles serialPort.DataReceived
Dim str As String = serialPort.ReadExisting()
Invoke(myDelegate, str)
End Sub
End Class
[/codesyntax]
Links
I uploaded the example VB.net app to https://drive.google.com/file/d/0B7mkEkhIEzkNMVVMZEZHbW8wUzA/view?usp=sharing