Categories

Microbit basic serial port example

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

comms app screenshot

Microbit Code

This was written in python using the Mu editor

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)

 

Application Code

Imports System.IO.Ports
 
 
Public Class frmMicroBit
    Dim WithEvents serialPort As New SerialPort
    Delegate Sub myMethodDelegate(ByVal 
 As 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 Sub
    Private 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 Sub
    Private 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 Sub
    Private 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 Sub
    Sub DisplaySerialText(ByVal myString As String)
        txtSerial.AppendText(myString)
    End Sub
    Private 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

 

Links

I uploaded the example VB.net app to https://drive.google.com/file/d/0B7mkEkhIEzkNMVVMZEZHbW8wUzA/view?usp=sharing

Microbit tune selector example

This example melds together our Microbit and an AD keypad and our Microbit built in tunes and allows you to play a different tune based on a key being pressed

We only selected 9 buttons of the 16 available

 

Code

from microbit import *
import music
 
while True:
    reading = pin1.read_analog()  
    sleep(100)
    if reading > 1 and reading < 39:
        music.play(music.DADADADUM)
    elif reading > 40 and reading < 94:
        music.play(music.ENTERTAINER)
    elif reading > 95 and reading < 164:
        music.play(music.PRELUDE)
    elif reading > 165 and reading < 218:
        music.play(music.RINGTONE)
    elif reading > 219 and reading < 290:
        music.play(music.FUNK)
    elif reading > 291 and reading < 354:
        music.play(music.BLUES)
    elif reading > 355 and reading < 418:
        music.play(music.BIRTHDAY)
    elif reading > 419 and reading < 485:
        music.play(music.WEDDING)
    elif reading > 486 and reading < 544:
        music.play(music.PUNCHLINE)
    else:
        num = 0

Microbit built in tunes

For the purposes of education and entertainment, the module contains several example tunes that are expressed as Python lists. They can be used like this:

import music
music.play(music.NYAN)

All the tunes are either out of copyright, composed by Nicholas H.Tollervey and released to the public domain or have an unknown composer and are covered by a fair (educational) use provision.

The tunes are:

DADADADUM – the opening to Beethoven’s 5th Symphony in C minor.
ENTERTAINER – the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.
PRELUDE – the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.
ODE – the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.
NYAN – the Nyan Cat theme (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).
RINGTONE – something that sounds like a mobile phone ringtone. To be used to indicate an incoming message.
FUNK – a funky bass line for secret agents and criminal masterminds.
BLUES – a boogie-woogie 12-bar blues walking bass.
BIRTHDAY – “Happy Birthday to You…” for copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853
WEDDING – the bridal chorus from Wagner’s opera “Lohengrin”.
FUNERAL – the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.
PUNCHLINE – a fun fragment that signifies a joke has been made.
PYTHON – John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).
BADDY – silent movie era entrance of a baddy.
CHASE – silent movie era chase scene.
BA_DING – a short signal to indicate something has happened.
WAWAWAWAA – a very sad trombone.
JUMP_UP – for use in a game, indicating upward movement.
JUMP_DOWN – for use in a game, indicating downward movement.
POWER_UP – a fanfare to indicate an achievement unlocked.
POWER_DOWN – a sad fanfare to indicate an achievement lost.

Code

from microbit import *
 
import music
built_in_tunes = [music.DADADADUM, music.ENTERTAINER, music.PRELUDE, music.ODE, music.NYAN, music.RINGTONE, music.FUNK, music.BLUES,
music.BIRTHDAY, music.WEDDING, music.FUNERAL, music.PUNCHLINE,music.PYTHON, music.BADDY, music.CHASE, music.BA_DING, 
music.WAWAWAWAA, music.JUMP_UP, music.JUMP_DOWN, music.POWER_UP, music.POWER_DOWN]
 
while True:
    for tune in built_in_tunes:
        music.play(tune)
        sleep(2000)

 

 

Microbit and a buzzer examples

MicroPython on the BBC micro:bit comes with a powerful music and sound module. It’s very easy to generate bleeps and bloops from the device if you attach a buzzer. Use crocodile clips to attach pin 0 and GND to the positive and negative inputs on the buzzer.

Here is a typical buzzer

buzzer

Now we will show a couple of basic examples

 

Code

We will be using music.pitch function, here is a little bit of information about this function first

music.pitch(frequency, len=-1, pin=microbit.pin0, wait=True)

Plays a pitch at the integer frequency given for the specified number of milliseconds. For example, if the frequency is set to 440 and the length to 1000 then we hear a standard concert A for one second.
If wait is set to True, this function is blocking.
If len is negative the pitch is played continuously until either the blocking call is interrupted or, in the case of a background call, a new frequency is set or stop is called.

The first example simply plays 3 different frequencies for different periods of time

from microbit import *
import music
 
while True:
    music.pitch(440,1000)
    sleep(1000)
    music.pitch(660,500)
    sleep(1000)
    music.pitch(880,750)
    sleep(1000)
    music.stop()
    sleep(1000)

The next example will play a different tone depending on whether button a or button b is pressed

from microbit import *
import music
 
while True:
    if button_a.is_pressed():
        music.pitch(440,1000)
    elif button_b.is_pressed():
        music.pitch(660,500)
    else:
        music.stop()

Microbit and LDR example

A photoresistor (or light-dependent resistor, LDR, or photocell) is a light-controlled variable resistor. The resistance of a photoresistor decreases with increasing incident light intensity; in other words, it exhibits photoconductivity. A photoresistor can be applied in light-sensitive detector circuits, and light- and dark-activated switching circuits.

A photoresistor is made of a high resistance semiconductor. In the dark, a photoresistor can have a resistance as high as several megohms (MΩ), while in the light, a photoresistor can have a resistance as low as a few hundred ohms. If incident light on a photoresistor exceeds a certain frequency, photons absorbed by the semiconductor give bound electrons enough energy to jump into the conduction band. The resulting free electrons (and their hole partners) conduct electricity, thereby lowering resistance. The resistance range and sensitivity of a photoresistor can substantially differ among dissimilar devices. Moreover, unique photoresistors may react substantially differently to photons within certain wavelength bands.

A photoelectric device can be either intrinsic or extrinsic. An intrinsic semiconductor has its own charge carriers and is not an efficient semiconductor, for example, silicon. In intrinsic devices the only available electrons are in the valence band, and hence the photon must have enough energy to excite the electron across the entire bandgap. Extrinsic devices have impurities, also called dopants, added whose ground state energy is closer to the conduction band; since the electrons do not have as far to jump, lower energy photons (that is, longer wavelengths and lower frequencies) are sufficient to trigger the device. If a sample of silicon has some of its atoms replaced by phosphorus atoms (impurities), there will be extra electrons available for conduction. This is an example of an extrinsic semiconductor

Here is a typical module that you can buy

 

ldr-module

 

 

Layout

 

ldr_bb

 

Code

In this example we will display the value of the LDR. In Mu , click on the Repl button and then cover the LDR

from microbit import *
 
while True:
    x = pin0.read_analog()
    print("value " + str(x))
    sleep(1000)

 

Here is another example, when the analogue value is below a certain value all the LEDs will switch on

from microbit import *
lights_off= Image('99999:99999:99999:99999:99999:')
lights_on= Image('00000:00000:00000:00000:00000:')
 
while True:
    display.show(lights_off)
    x = pin0.read_analog()
    print("value " + str(x))
    if x>300:
        display.show(lights_on)
    sleep(1000)