BBC Microbit

The BBC micro:bit is a pocket-sized codeable computer with motion detection, a built-in compass and Bluetooth technology, which was given free to every child in year 7 or equivalent across the UK in 2016. 

It measures 4cm by 5cm, is available in a range of colours, and designed to be fun and easy to use. It can be coded with something simple in seconds – like lighting up its LEDs or displaying a pattern – with no prior knowledge of computing.

It also connects to other devices, sensors, kits and objects, and is a companion to Arduino, Galileo, Kano, littleBits and Raspberry Pi, acting as a spring board to more complex learning.

Each element is completely programmable via easy-to-use software on a dedicated website microbit.org, that can be accessed from a PC, tablet or mobile.
The BBC Micro Bit IDE
There are several IDE platforms for coding the Micro Bit, the most popular being the Python Editor and the JavaScript Blocks Editor; both of which are accessible online here: http://microbit.org/code/ 
 
To keep things as simple as possible, the following sections contain code that was developed using the JavaScript Blocks Editor.

Open the JavaScript Blocks Editor from the link above.

 

There are three main areas on the screen. On the right hand side is the coding area where you build your code using the JavaScript Blocks. The JavaScript Blocks are selected from the menu in the middle of the screen. On the left of the screen is the simulator (this can be hidden by clicking the button to the left hand side of the “download” button.

There are buttons at the top of the screen where you can toggle between the Blocks editor and the JavaScript editor, which could be useful if you are more familiar with the latter. There is the facility to name each of your projects (or versions of) before saving them and/or downloading them. 

The “Projects” button will reveal your saved projects as well as some example projects. 

There are many tutorials online and I suggest that you try one or two of them as well as spending some time navigating your way around the IDE.

The examples that follow later do not require the reader to have expert knowledge of programming as most of the programs are quite straight forward and easy to follow.

Once you are comfortable with constructing a simple program, downloading it and transferring the hex file to the Micro Bit, you will be equipped to progress to the following examples.
Magnetometer
The Micro Bit  has a built-in magnetometer chip which is intended for use as a compass to detect magnetic north. This requires calibration. It also very good for detecting the presence of a magnet!

Open the JavaScript Blocks Editor and contruct a program as follows:


 


Save the file (hex file) and upload it to your Micro Bit. Whilst the Microbit is connected, open the Arduino IDE and launch the serial monitor (after selecting the required serial port).Set the baud rate to 115200. You should see somethis similar to the following output. 
The Arduino IDE is covered in some detail in “Light Sensor” later in this Section..

 

Changing the sample rate to 10 ms,  the data is smoothed as in the diagram below. This diagram was generated using MakerPlot which is a very good graphical appliocation. It is explained in more detail elsewhere.

 

Light
LED
We’ll start by attaching an LED to the Micro Bit via a breadboard. Rather than using alligator clips or some other means to connect components to the Micro Bit, attaching components to the Micro Bit via a solderless breadboard is much easier and is also much more flexible as the breadboard can accommodate several components at the same time. I personally use a Breakout T-Adaptor which fixes onto a breadboard and the Micro Bit slots into it.

Attach the ground pin (shortest pin) to the ground pin of the Micro Bit. Attach the other (longer pin) if the LED to pin 0 (P0) of the Micro Bit via a 470 ohm resistor.


 

Micro Bit LED Circuit Diagram


Now everything that we need is connected to the Micro Bit, we now need to do a little coding.

Open the JavaScript Blocks Editor and construct the following blocks:


 


Writing the value “1” to P0 will turn the LED on. There will then be a pause of 1 second (1000 milliseconds before the LED is turned off by writing the value “0” to P0. There will then be another pause of 1 second before the whole process begins again. The commands are grouped in a “forever” block so the process will loop and continue whilst the Micro Bit is turned on.

Save the file (hex file) and upload it to your Micro Bit. You will see the LED turning on and off. You could try changing the length of times of the pauses to get different effects. You could add more LEDs to the system and program them to do a coordinated display.






RGB
An RGB LED has four legs:  one to drive each of the three component colours and one, the longest pin, is used by all other components in the LED.

By supplying current to the shorter pins (red, green, blue). The LED will shine. Any colour can be made by varying the intensities of the red, blue and green components. 

Set up the circuit as below, placing 220 ohm resistors before each of the shorter pins on the RGB module. 

 
Micro Bit RGB Circuit Diagram

Initially we will write to each of the components using digital write. The value for each write will either be 1 (on) or 0 (off). Construct a program using the JavaScript Blocks Editor similar to the one below.

 
Save and download your program then load it onto the Micro Bit. You will see that the LED will scroll between colours. 

You can fade each of the RGB components to achieve a smooth transition between colours (and also achieve a much bigger range of colours) by using analog write. With this method you can write a value of between 0 (completely off) to 1023 (full on) for each pin.

Try altering the values for each of the pins and the pause times to achieve your very own light show.
Traffic Light Display Module
These small modules are designed for inclusion in model projects. As the name suggests, they can be used in projects and simulations involving traffic lights. 

The module consists of three LEDs; red, yellow and green. You will need to connect these up to separate pins on the Arduino so that you can make them turn on and off individually. In the example below, I have connected the LED pins as follows:

Green LED Micro Bit pin 0
Yellow LED Micro Bit pin 1
Red LED Micro Bit pin 2

We need to decide on the sequence that the LEDs should turn on and off. Real traffic lights (in the UK at least) turn on and off in the following sequence:

Red
Red/Yellow
Yellow
Green
Yellow

By putting pauses (delay commands) between each step of the sequence, you can achieve a pretty good representation of real traffic lights.


 

Save and download your program then load it onto the Micro Bit.
You will see that the sequence is continuously followed and, as the program is a loop, the sequence will just continue to run and run.

Try experimenting by altering the delay times to achieve a more realistic representation of real traffic lights.




 
Sensors
Tilt Sensor
These sensors are quite basic. They contain a ball bearing that moves when the sensor is tilted. This change of state is what is what is detected.

Set up the circuit on a solderless breadboard by including a 10k ohm pull up resistor.


 

Micro Bit Tilt Sensor Circuit Diagram

We will digital read the pin. The values will be either 1 (there has been a change of state i.e. the sensor has “tilted” since the last read) or 0  (there has been n0 change of state i.e. the sensor has not “tilted” since the last read). I have included a pause of 1 second between readings (1000ms) and a line to display “TILT” on the Micro Bit LED display when tilt is detected.

Construct a program using the JavaScript Blocks Editor similar to the one below.

 

Save and download your program then load it onto the Micro Bit.
The tilt sensor can be used in many projects such as home security by detecting when doors or windows are opened, personal monitoring of the vulnerable by detecting if the person falls or even security of say a laptop bag by detecting of the bag is moved. Obviously these suggested projects would have to contain other components and would require more programming.
Light Sensor
The LDR Sensor is a resistive sensor. As the light entering changes, the resistance of the current passing through it will change. It is this change that we will monitor. 

The sensor requires 5 volts so you will have to supply that from an external source rather than the Micro Bit. A 10k ohm resistor is also required.

Set up your circuit as follows, remembering that you need an external 5 volt supply.

 
Micro Bit LDR Sensor Circuit 

Using the JavaScript Block Editor, construct your program to analog read pin0. Using analog read will produce sensor values between 0 and 1023.  I have included a 1 second (1000ms) pause between readings to make them easier to read.

Your blocks should look something like the following:

 

We could display these readings on the Micro Bit’s LED screen but the readings would be clearer if we used a serial monitor. This is why I have included the serial write commands in the code above.

If you are familiar with the Arduino IDE (see Arduino Section), you could use that to monitor the data from the sensor.

If you don’t already have the Arduino IDE installed, you can download it here: 

https://www.arduino.cc/en/Main/Software

Once you have downloaded and installed the software, you will need to connect your Micro Bit to the device that is running the Arduino IDE (don’t forget to save your Micro Bit program and load the hex file onto the Micro Bit).

If your Micro Bit is attached to your device, you now need to select the port that it is attached to. In my case it is COM5:


 

Now we need to select the board. At the time of writing, the support for the Micro Bit had to be installed into the IDE.

Open the Arduino IDE and select “File” then “Preferences”.
Insert the following into “Additional Board Manager URL”:

https://sandeepmistry.github.io/arduino-nRF5/package_nRF5_boards_index.json

Go to “Tools”, “Board” and under Nordic Semiconductor NRF5 select BBC micro bit

 

Finally open the serial monitor:

 
You will see that the resistance values are appearing every second (1000ms) just as you programmed it to. Cover the sensor and you will see this value change.

 

You can add an LED to the circuit and with a bit of extra programming you could make the light come on when the ambient light fades to a certain level; a nice little project that can be adapted for the home.


Humidity & Temperature: KY 015 Sensor
The KY 015 Humidity & Temperature Sensor is a very useful component. These and other variants (DHT-11) etc can be bought online quite cheaply. 

The measured humidity is quite accurate but for more precise and accurate temperature measurement, I would recommend the LM35 precision analog temperature sensor. The connection is straight forward. Connect the centre pin to pin13 of the Micro Bit and connect the outside pins to the corresponding GND and 3V points.


 

KY 015 Humidity & Temperature Sensor Circuit

In the JavaScript Blocks Editor you will need to add the DHT-11 blocks. This is done by selecting “Add Package” from the blocks selection area in the centre of the IDE.

The program is quite straightforward. We need to read the temperature and humidity and write the values to the serial monitor. I have added some text to make the serial output neater and more meaningful. I have also added a line to separate each set of readings.

 

Save the program and upload the hex file to the Micro Bit. Connect the Micro Bit to the device that has the Arduino IDE installed.

Using the serial monitor of the Arduino IDE (as described under LDR Light Sensor earlier) you will see that the temperature and humidity are updated every 5 seconds (5000ms).

 

KY 015 Sensor Serial Output 

This sensor is easy to set up and can be used of part of bigger projects e.g. a weather station or monitoring a greenhouse.

PIR Motion Detector
PIR motion detectors are widespread as they are used in many security systems to detect events such as trespass or other motion. The modules themselves are quite inexpensive and can be readily bought from numerous sources on the internet.

They have a range of detection of about 6–7m and are highly sensitive. When the PIR motion sensor detects motion, it outputs a 5V signal to the Arduino and triggers an interrupt. 

 

PIR Motion Sensor top view


On the underside of the module, you will see that there are three pins:

 

For convenience, attach the PIR motion sensor module to a solderless breadboard then connect the pins as follows:
PIR Sensor Pin Micro Bit Pin
OUT Pin 0
GND GND
VCC 5v*

*Note: the module requires 5 volts which it cannot get from the Micro Bit. You will need to supply an alternative, external 5 volt supply to the circuit.

There are two potentiometers labeled time (or T) and sensitivity (or S) on the underside of the sensor module. Adjusting the sensitivity changes the detection range from 3m to up to 7m. As the range increases, the more sensitive to movement it becomes.

Time represents the duration of the output signal. If it detects movement, the time parameter controls how long the sensor will output high. This can be changed from 5s through to 300s.

Using the JavaScript Blocks Editor, I have written a program that will read pin 0 every 1 second (1000ms). If motion is detected (i.e. there has been an interrupt triggered), the digital pin (pin 0) will read “1” and a message will appear on the Micro Bit LED display.  

 

The PIR sensor is a convenient way to add movement detection functionality to larger projects. You could add it to a home security project or incorporate it in a project to automatically take photographs when a person or animal passes in front of the sensor (see the Arduino Section where the latter is detailed for the Arduino).




Ultrasound Distance Measurement 
The HC-SR04 module uses ultrasound sonar to measure the distance to an object. It consists of two ultrasonic transmitters, a receiver and a control circuit. It can measure the presence objects accurately between 4cm and 400cm.

These modules are used in many applications, the most common being in projects that require object avoidance such as remote controlled cars and robotics.


 

HC-SR04 Ultrasound Module

The module requires 5 volts which it cannot get from the Micro Bit, so an alternative 5V power source will need to be applied to the circuit.. 

Connect the GND to GND on the Micro Bit, Trig to P0 and Echo to P1. For convenience I did this via a solderless breadboard.

The basic JavaScript Blocks below will result in displaying the distance measured by the sensor on the Micro Bit each time Button A is pressed.


 


As well as showing distance on the Micro Bit, the next program will display the distance in the serial monitor of the Arduino IDE (see earlier how to set the serial monitor up). On the Micro Bit LED display, each reading will be displayed for 1 second, the screen will then clear and then pause for a further second will occur before the next press of the button.

 

Using the serial monitor of the Arduino IDE (as described under LDR Light Sensor earlier) you will see that the measured distance is displayed. This is updated each time Button A on the Micro Bit is pressed.

 

HC-SR04 Serial Output

The sensor was moved forwards and backwards in relation to a wall. As you can see, the distance changed each time. 

You could remove the necessity for the button to be pressed to gain a reading by just using pause commands to set the timing of readings.

Soil Moisture Sensor
These modules, on the face of it, could prove to be very useful in monitoring soil moisture in the home, greenhouse or even outdoors. They have had varying reviews, some good and some bad, but I won’t go into them here, I’ll just explain how to set one up and monitor the data that it produces.

The soil moisture meter is quite easy to connect to a Micro Bit. For convenience, I did this via a solderless breadboard. 

 

Micro Bit Soil Moisture Sensor Circuit

In the JavaScript Blocks Editor, add the Soil Moisture package that will give you access to the necessary blocks. Follow the steps below to set up the Micro Bit for receiving and processing the moisture data.

The following program will read pin 1 (soil moisture reading) and then write the value in a serial monitor as well as on the Micro Bit LED display.

 

Using the serial monitor of the Arduino IDE (as described under LDR Light Sensor earlier) you will see that the reading is displayed every half second (500ms).

 

Moisture Sensor Serial Output

You will also see that the moisture reading is written to and displayed on the Micro Bit LED display. 

Try adding more water to your system to see the readings increase. Try the sensor in different media, with different amounts of moisture or under different conditions to see different effects. You may add this to a larger monitoring project in the future.
Sound Sensor
A sound sensor can, and is, a very useful item. It can be used to trigger lights, doors, alarms etc or even used to control a smart vehicle. 
The sensor detects sound through a microphone and this sound is passed through a LM393 op amp. The particular one used here has an operating voltage of 3.3V-5V and has a signal output indicator LED which comes on when a sound is detected. The output is low when there is sound and high when there is no sound (i.e. LOW and HIGH pin states respectively. 
As the output is digital, we can only detect when there is sound detected or not. If we wanted to detect relative levels of sound, we would need a module that has an analog output. The three pin version of this module connects to the Micro Bit as follows:

VCC 5V
GND GND
OUT Pin 0
As the output is digital, we can only detect when there is sound detected or not. If we wanted to detect relative levels of sound, we would need a module that has an analog output.
Connect the module to your Micro Bit as above and then connect the Micro Bit to your computer. Compile a program to read the digital state of the input on pin 0. You can use the blocks that were constructed earlier for reading the digital output of the PIR detector.

 

If you change the string value from “Motion” to “Sound”, each time that the PIR detector detects souns, the Microbit will display the word “Sound”. 
Microwave Radar Sensor

The microwave radar sensor uses Doppler radar technology, with auto-sensing capabilities to control other components  It has high sensitivity and  reliability. It is widely used in lighting applications anti-theft alarms. It is important to note that the target must be moving toward or away from the sensor to activate it.

Connect the sensor to the Micro Bit as follows:

VCC 5V
GND GND
OUT Pin 0
Using the JavaScript Blocks Editor, the program is written so that the value of pin 0 will be read every 1 second (1000ms). If motion is detected, the digital pin (pin 0) will read “1” and a message will appear on the Micro Bit LED display.  

 

Rather than have the message just appear on the Micro Bit LED display, you could add a line to the program to write to the serial port when motion is detected..

 

A blank line has been added after each time that “Motion” is written to make it easier to read the serial output.
 

The microwave radar sensor is a convenient way to add movement detection functionality to projects. It can be added to a home security project or incorporated  into a project to automatically take photographs when a person or animal passes in front of the sensor (see the Arduino Section where the latter is explained in some detail for the Arduino using a PIR sensor).
Reed Sensor 
A reed switch is an electrical switch operated by an applied magnetic field The Reed sensor module is also known as a magnetron module or reed switch. It has a working voltage 3.3V-5V, with a digital output which is capable of switching output (0 and 1)
This module can be incorporated into program-controlled switches, copiers, washing machines, refrigerators, cameras, electromagnetic relays, electronic weighing scales, level meters, gas meters, water meters and so on.
Connect the sensor to the Micro Bit as follows:

VCC 5V
GND GND
OUT Pin 0
Using the JavaScript Blocks Editor, the program is written so that the value of pin 0 will be read every 1 second (1000ms). If motion is detected, the digital pin (pin 0) will read “1” and a message will appear on the Micro Bit LED display.  The program can be adapted from any of the previous programs above that read the digital pin pin 0, for example the following program could be used.

 
 
Hall Effect Sensor 
A Hall effect sensor is a transducer that varies its output voltage in response to a magnetic field. Hall effect sensors are used for proximity switching, positioning, speed detection, and current sensing applications.

In a Hall effect sensor, a thin strip of metal has a current applied along it. In the presence of a magnetic field, the electrons in the metal strip are deflected toward one edge, producing a voltage gradient across the short side of the strip (perpendicular to the feed current). Hall effect sensors have an advantage over inductive sensors in that, while inductive sensors respond to a changing magnetic field which induces current in a coil of wire and produces voltage at its output, Hall effect sensors can detect static (non-changing) magnetic fields.

When no magnet is present, the signal is HIGH
When a magnet is present, the signal is LOW

Connect the sensor to the Micro Bit as follows:
VCC 5V
GND GND
DO pin 12

AO pin 10

Using the JavaScript Blocks Editor construct the following program and upload it to the Micro Bit.

 

Open the Arduino IDE serial monitor (see earlier in this Section) to see the output.

 
A clearer respresentation of the output can be obtailed by using a graphical program such as Maker Plot (see earlier).

 

Comparing the Hall Sensor with the built in magnetometer is quite straightforward. Connect the sensor to the Micro Bit as before (AO of the sensor connected to pin 10 of the Micro Bit). Open the JavaScript Block Editor and construct a program to read the sensor as well as to read the Micro Bit’s magnetometer. Your blocks should look something like this: 

 

Note the comma to separate the data points and a blank line after each set of data is taken. Save your program and upload the hex file to the Micro Bit. Open a Serial Monitor. 

You will see that every 100 milliseconds, two values will appear. The first is the analog value of pin 10 (the Hall sensor) and the second is the magnetic force of the Micro Bit’s magnetometer. By moving a magnet various distances from the Hall sensor and the Micro Bit, you will see the values change.

 

To illustrate the changing magnetic field, close the serial monitor and open Maker Plot. Select the correct port and baud rate. Alter the values of the x and y axes to cater for your data and begin collecting.

 

The Micro Bit’s built in magnetometer values are plotted in red. As the magnetic force increases, so does the value on the graph. The Reed sensor analog values are plotted in black. As the magnet gets nearer to the sensor, the analog value decreases.
Capacitive Touch Sensor 
Touch sensors work similar to a switch. When they are subjected to touch, pressure or force they get activated and acts as a closed switch. When the pressure or contact is removed they act as an open switch The capacitive touch sensor has low power consumption and requires a power supply of 2 ~ 5.5V DC

Connect the sensor to the Micro Bit as follows:

VCC 5V
GND GND
OUT Pin 0
As the output of the sensor is digital, the program is quite simple. Using the JavaScript Blocks Editor construct the following program and upload it to the Micro Bit.

 


Open the Arduino IDE serial monitor (see earlier in this Section) to see the output.

 

When the sensor is touched, the word “pressed” is displayed in the serial monitor.This module can be incorporated into numerous projects and can replace the traditionally used push button switch.
Flame Detection Sensor
The 4 pin flame detection sensor is generally an IR infrared receiver which can detect IR radiation between 760 nm and 1100 nm. The module has a detection angle of 60 degrees and sensitivity is adjustable using the on-board digital potentiometer. It has an operating voltage of 3.3V to 5V and outputs of both digital and analog.
To test the module, a flame should be set of approximately 80cm from the sensor. If using a flame larger than that given by a lighter, this will be detected at a greater distance. Connect the module to the Micro Bit as below.
VCC: VCC.
GND: GND.
DO: not connected
AO: Pin 0.
Construct the following program and upload it to the Micro Bit. Note that the program will read the analog output of the sensor.
 

Open either the Arduino IDE serial monitor or a graphical program such as Maker Plot.
 


If you expose thasensor to a naked flame, you will see that the digital signal will change with the intensity of the flame.




 
Physical Input
Push Button
As you are aware, the Micro Bit has two buttons. If you need any more buttons you can easily add some via a breadboard. Outlined below is how to add one but adding more shouldn’t be a problem.

The common push button component is a small, tactile switch identical to the ones on the Micro Bit. These switches are normally open and so must be pushed to close the circuit. 

One pin of the button should be connected to 3V on the Micro Bit, the other pin to pin0 of the Micro Bit. When the button is pressed, pin0 reads True or 1.

The Micro Bit has internal pull-up and pull-down resistors. When a digital input is read, the pull-down resistors are turned on so there is no need for an external one.

 
Micro Bit Push Button Circuit

Open the JavaScript Blocks Editor and construct a program similar to the one below. 

 

Save the program, download it and upload the hex file to the Micro Bit.

The word “Button” will scroll across the Micro Bit LED display when the button is pressed. There will then be a pause for 1 second (1000ms). If the button isn’t pressed after that, nothing will be displayed until the button is pressed again.

Add more buttons and program them to display different messages on the Micro Bit or even to perform different functions.
Potentiometer
A potentiometer is a simple knob/dial that provides a variable resistance, which can be read by the Arduino as an analog value. They circuit set up is quite simple A potentiometer is quite easy to connect to a Micro Bit. For convenience, I did this via a solderless breadboard. 

 
Micro Bit Potentiometer Circuit Diagram

In the JavaScript Blocks Editor, add the Potentiometer package that will give you access to the necessary blocks. Follow the steps below to set up the Micro Bit for receiving and processing the potentiometer data.

 

Using the serial monitor of the Arduino IDE (as described under LDR Light Sensor earlier) you will see that the reading is displayed every half second (500ms).

 

You will also see that the potentiometer reading is written to and displayed on the Micro Bit LED display. 

As you work with other components and more complex circuits, you will undoubtedly need to us potentiometers.


 
Sound
Continuous Buzzer
The continuous buzzer has two terminals. Connect the short terminal to GND and the long terminal to pin0 on the Micro Bit (Pin 0).

You will notice that the code blocks that we will use here are the same as those used for the LED earlier in this section. Construct the following blocks in the JavaScript Blocks Editor and upload the program to the Microbit.

 

All that this program does is change the charge to pin 0 from 1 (high) to 0 (off) with a pause of 1 second (1000ms).

Save your project, download it and install the hex file on the Micro Bit. You should hear the buzzer sounding cyclically. If you play around with timings, I’m sure that you be able to compose a tune.



 
Data
Data Logging: Micro Bit File System
The in-built package allows reading files from and writing files to the Micro Bit flash memory. The entire file system content is erased when a new .hex file is downloaded onto the Micro Bit. The following example initially creates a file (output.txt) and then appends (adds) text to the file. This is then read and displayed in the serial monitor.

 

Compile the program using the JavaScript Blocks Editor, save it and upload the hex file to the Micro Bit, Open the Arduino serial monitor. You should see the following.
 

Rather than programming text(data) to be written to and from the Micro Bit, we can write real data that is generated directly. Using the internal magnetometer we can log data to a file on the Micro Bit and then read it via the serial monitor.

Compose a program using JavaScript Blocks Editor as below. This logs 20 data points to the file “force.txt” on the Micro Bit and then reads the file and displays the data on the serial monitor.

 

Save the program and upload it to the Micro Bit. Open the serial monitor. You should see an output similar to the one below.

 

It must be remembered that he entire file system content is erased when a new .hex file is downloaded onto the Micro Bit.
 
Data Logging: MakerPlot

The background of MakerPlot is described earlier under Arduino: Data Logging: MakerPlot. 

For the purpose of illustrating the logging of data using MakerPlot, I have written a program to monitor temperature and light. 

Using the Micro Bit JavaScript Blocks Editor construct a program to collect the data.

 

The program writes the temperature value to the serial port. There is then a comma “,” to separate that value from the humidity value that will come next. A blank line is then written to the serial port to separate that set of data from the next set. There is then a pause of 5 seconds (5000ms) before the next readings are processed.

Save the program, download it and then upload the hex file to the Micro Bit. Open the MakerPlot program.

From the first screen of Maker Plot, select “Run Standard Interface”.

We will be collecting temperature and light data every 5 seconds so we need to alter the axes accordingly. I set the x-axis to 2.5 minutes and the y-axis to 200:

 


Now select the port and baud rate (115200 for Micro Bit):

 

Select “Log To File” in the bottom panel. 
MakerPlot is now ready to receive the sensor data. Click the Control Switch to begin data acquisition.

 

Above is the resulting sensor data plot. The light values are the higher values and the temperature values are the lower values. Open the std_dat.txt file to see the raw data. Here is a screenshot of a portion of my data file:

 

You can save this file and then import into Excel for some further analysis/plotting.

Try logging other data from the Micro Bit. Below I have set up a program to export Accelerometer data to MakerPlot:

 
Open Maker Plot to see a plot of the Accelerometer data.

 


I have only scratched the surface of this excellent program and I’m sure that once you have tried the other applications that are included, you will purchase a copy.







 
Visual Displays
The display on the Micro Bit is sufficient for quite a lot of applications but if you aren’t a fan of the scrolling messages and want something easier to read, then an external display is the answer.
 
OLED
The 0.96 inch OLED display uses I2C communication and is made of 128 by 64 individual OLED pixels. The fact that the display uses I2C communication means that it can communicate with a microcontroller using just 2 pins. These two pins correspond to SDA and SCL on pins 20 and 19 on the Micro Bit respectively.

The wiring scheme for the Micro Bit is as follows:


Pin Label Micro Bit pin I2C Function
GND Ground Ground
VCC Power Power
SDA P20 SDA (serial data in)           
SCL P19 SCL  (I2C clock)            


 

Micro Bit OLED Circuit

Once you have the Micro Bit OLED circuit constructed, open the JavaScript blocks Editor and construct a program to display text and data on the OLED display.

Firstly add the OLED package to the Micro Bit IDE. Secondly we have to initialise the size of the OLED display. I have added an extra line of code to clear the display on start-up.

 

Construct the main part of your program similar to the blocks below. Here, I have opted to display temperature and light levels which will be updated every 5 seconds (500ms).

I have added a couple of text strings, each to precede the data reading. Finally, the display will clear before the next set of data is displayed.

 

The display of data should look something like this:

 

Try altering the program to display magnetometer or accelerometer data or even just to display text. This small display is so easy to work with as connecting it up is so simple. I’m sure it will feature in your future projects.

 
Motors
Servo Motor
Servo motors are used in a whole host of applications from robotics and model aeroplanes to dispensers and scanners. They can be purchased online relatively cheaply.

The servo motor generally has three wires and should be connected to the Micro Bit as follows:

Servo Wire Colour Data Sheet Label Micro Bit Pin
Red VCC (+) 3V pin
Brown Ground (-) GND pin
Orange PWM (Signal) Pin 0

 
Micro Bit Servo Motor Wiring Diagram

Servo motors can generally turn from 0 to 180 degrees so we will program it to turn to specific angles. 
Using the JavaScript Blocks Editor construct a program to turn to specific angles and pause at each angle for 1 second:


 

Save the program and load the hex file onto the Micro Bit. You will see that the motor will stop at the 180 degrees position for 1 second (1000ms) then turn to the 90 degrees position where it will stop for 1 second. Finally it will return to the 0 degrees position, stopt for one second before the whole process begins again. 

Try experimenting with different angles and pause times in your program. Think how you can use these motors in future projects. If you want to progress onto controlling a servo motor remotely there is a method of developing an Android app to control such a motor later in this book.
Stepper Motor with ULN2003 Driver
Stepper motors are used for position control. They divide a full rotation into a number of equal “steps” so can be programmed to move to specific positions. They are usually found in desktop printers, 3D printers, CNC to milling machines, and anything else that requires precise positioning control. 

ULN2003 IC is one of the most commonly used Motor driver integrated circuits (IC) generally used when there is a need to drive high current loads using digital logic circuits like Timers, Gates, microcontrollers etc.

This example will show how to control a 28BYJ-48 stepper motor by using a ULN2003 driver board and Micro Bit.

Usually, the 28BYJ-48 stepper motor comes with a 5-pin connector that will fit to the ULN2003 driver board .Connect the ULN2003 driver board to four digital pins on the Micro Bit as follows:

Micro Bit ULN2003 Board
DigitalPin.P0  IN1 
DigitalPin.P1 IN2 
DigitalPin.P3 IN3 
DigitalPin.P8                IN4 

Compile, download and then upload the following JavaScript program to the Micro Bit.

let pause = 0
basic.forever(() => {
    if (input.buttonIsPressed(Button.B) && !(input.buttonIsPressed(Button.A))) {
        basic.showLeds(`
            . # . . .
            . . # . .
            . . . # .
            . . # . .
            . # . . .
            `)
        pause = 0
        while (input.buttonIsPressed(Button.B)) {
            for (let i = 0; i < 2; i++) {
                for (let i = 0; i < 1; i++) {
                    pins.digitalWritePin(DigitalPin.P0, 1)
                    pins.digitalWritePin(DigitalPin.P1, 0)
                    pins.digitalWritePin(DigitalPin.P2, 0)
                    pins.digitalWritePin(DigitalPin.P8, 1)
                }
                basic.pause(pause)
                for (let i = 0; i < 1; i++) {
                    pins.digitalWritePin(DigitalPin.P0, 0)
                    pins.digitalWritePin(DigitalPin.P1, 0)
                    pins.digitalWritePin(DigitalPin.P2, 1)
                    pins.digitalWritePin(DigitalPin.P8, 1)
                }
                basic.pause(pause)
                for (let i = 0; i < 1; i++) {
                    pins.digitalWritePin(DigitalPin.P0, 0)
                    pins.digitalWritePin(DigitalPin.P1, 1)
                    pins.digitalWritePin(DigitalPin.P2, 1)
                    pins.digitalWritePin(DigitalPin.P8, 0)
                }
                basic.pause(pause)
                for (let i = 0; i < 1; i++) {
                    pins.digitalWritePin(DigitalPin.P0, 1)
                    pins.digitalWritePin(DigitalPin.P1, 1)
                    pins.digitalWritePin(DigitalPin.P2, 0)
                    pins.digitalWritePin(DigitalPin.P8, 0)
                }
                basic.pause(pause)
            }
        }
    }
})
basic.forever(() => {
    if (input.buttonIsPressed(Button.A) && !(input.buttonIsPressed(Button.B))) {
        basic.showLeds(`
            . . . # .
            . . # . .
            . # . . .
            . . # . .
            . . . # .
            `)
        pause = 0
        while (input.buttonIsPressed(Button.A)) {
            for (let i = 0; i < 2; i++) {
                for (let i = 0; i < 1; i++) {
                    pins.digitalWritePin(DigitalPin.P0, 1)
                    pins.digitalWritePin(DigitalPin.P1, 1)
                    pins.digitalWritePin(DigitalPin.P2, 0)
                    pins.digitalWritePin(DigitalPin.P8, 0)
                }
                basic.pause(pause)
                for (let i = 0; i < 1; i++) {
                    pins.digitalWritePin(DigitalPin.P0, 0)
                    pins.digitalWritePin(DigitalPin.P1, 1)
                    pins.digitalWritePin(DigitalPin.P2, 1)
                    pins.digitalWritePin(DigitalPin.P8, 0)
                }
                basic.pause(pause)
                for (let i = 0; i < 1; i++) {
                    pins.digitalWritePin(DigitalPin.P0, 0)
                    pins.digitalWritePin(DigitalPin.P1, 0)
                    pins.digitalWritePin(DigitalPin.P2, 1)
                    pins.digitalWritePin(DigitalPin.P8, 1)
                }
                basic.pause(pause)
                for (let i = 0; i < 1; i++) {
                    pins.digitalWritePin(DigitalPin.P0, 1)
                    pins.digitalWritePin(DigitalPin.P1, 0)
                    pins.digitalWritePin(DigitalPin.P2, 0)
                    pins.digitalWritePin(DigitalPin.P8, 1)
                }
                basic.pause(pause)
            }
        }
    }
})
basic.forever(() => {
    if (!(input.buttonIsPressed(Button.A)) && !(input.buttonIsPressed(Button.B))) {
        basic.showLeds(`
            . . . . .
            . . . . .
            . . . . .
            . . . . .
            . . . . .
            `)
        for (let i = 0; i < 1; i++) {
            pins.digitalWritePin(DigitalPin.P0, 0)
            pins.digitalWritePin(DigitalPin.P1, 0)
            pins.digitalWritePin(DigitalPin.P2, 0)
            pins.digitalWritePin(DigitalPin.P8, 0)
        }
    }
})

It uses buttons A and B to drive the stepper Clockwise or Counterclockwise

The repeat blocks could be removed but they grouped the code nicely plus you could easily change them to move more per button press : 


 
Communication
Bluetooth BLE
The Micro Bit is equipped with a version of Bluetooth, known as Bluetooth Low Energy (BLE). This can be used to communicate with other Bluetooth-enabled devices such as tablets and smartphones. The application of this will be explored later but here we will write a program for the Micro Bit use Serial Bluetooth Terminal to view the Bluetooth output from the Micro Bit.

Download and install Serial Bluetooth Terminal from the App Store and install it on a Bluetooth-enabled device.

To produce a basic BLE app, open the JavaScript Blocks Editor and add the Bluetooth package. Add the Bluetooth UART service to the on start block. I have added a block so that when Button A is pressed, the word “Hello” is sent.

 

Save your program and download it before installing the hex file on the Micro Bit.

You now need to connect your Android device to your Micro Bit using Bluetooth. If you haven’t already paired your device, you will need to do so. Instructions on how to do this can be found here: http://microbit.org/guide/mobile/

Launch Serial Bluetooth Terminal on your Android device and connect to the Micro Bit. Now, when you press Button A on the Micro Bit and the word “Hello will appear in the terminal window.

There isn’t much programming involved in the example above. You can build on this program to add messages to be displayed on the Micro Bit LED. Below is an example of what you could do.

Firstly, I have added a welcome message and a smiley face at the beginning of the program;

 

Next I have added a tick to appear when the Micro Bit is connected to the Android device:

 

When the connection is not active or has been broken, I wanted a message on the LED display to reflect this; I thought that a big “X” would be appropriate:

 


You can try adding code for Button B to send a different message to the Android device. Here are my JavaScript blocks for the two buttons:

 

Finally I have added a block to enable a different graphic to appear on the LED display when data is received by the Micro Bit. This is something that will be covered later in this book.

 

There is much more to the Micro Bit Bluetooth Package and this has only been a very brief introduction. BLE will be greatly expanded on in later where it will form the basis of Micro Bit Android applications.
Bluetooth HC-05
Rather than use the Micro Bit’s built in BLE. You can use an external module such as the HC-05 Bluetooth module. Using the HC-05 module is a very convenient way of adding Bluetooth functionality to a whole range of microcontrollers, not just the Micro Bit.

The connections to the Micro Bit are as follows:

HC-05 Micro Bit
GND GND
VCC VCC
RXD TX
TXD RX
KEY VCC
STATE none

I have constructed a program using the Micro Bit JavaScript Blocks Editor. The first block directs the serial to pin 0 (for transmit) and pin1 (to receive). The baud rate is set to 9600.

 

Now we need to send some information using the HC 05 Bluetooth module.
The most convenient method to send information is by using the buttons on the Micro Bit. 

To get the pressing of Button A to send a message, we need to use the on button pressed block. I have added an LED to the circuit on pin 2 so we will digital write the value 1 to pin 2 to turn the LED on. I have added the message “Hello from Button A” as the message to be transmitted.

 


Similarly, to get the pressing of Button B to send a message, we use the on button pressed block. I have added digital write the value 0 to pin 2 to turn off the LED and I have added the message “Hello from Button B” as the message to be transmitted.

 

Save your program and download it before installing the hex file on the Micro Bit.

Now download and install Serial Bluetooth Terminal from the App Store and install that on a Bluetooth-enabled device.

You now need to connect your Android devise to your Micro Bit using Bluetooth. If you haven’t already paired your device, you will need to do so. Instructions on how to do this can be found here: http://microbit.org/guide/mobile/

On the Bluetooth-enabled device start the Serial Bluetooth Terminal app and scan for available Bluetooth devices by selecting Devices from the dropdown menu. The resulting list should contain your Micro Bit. Select your Micro Bit and select Terminal from the drop down menu. Click the connect symbol to connect to the Micro Bit. Messages will begin to appear in the Terminal window as you connect.

Once connected, press the buttons on the Micro Bit and you will see the different messages appear in the Terminal window of the Android device.

This method of using the HC-05 Bluetooth module in conjunction with the Micro Bit could form the basis of many more complex projects.



 
Integrated Circuits
Shift Register 74HC595N
A 74HC595 shift register is an integrated circuit that converts serial information to parallel. It requires 3 pins (as well as power and ground) from a microcontroller but allows us to have a total of 8 outputs. Earlier in this Section we have seen that we used one pin on the Micro Bit to control one LED but by using a 74HC595  shift register, we can control 8 LEDs using only 3 pins. 

 

For illustration purposes, the examples below will use the 74HC595N shift register and we will use pins 0, 1 and 2 on the Micro Bit to control it. Pin 0 is connected to the data pin, pin 1 is connected to the clock pin and pin 2 is connected to the latch pin.
 
The first program illustrates the basic steps needed to control the 8 LEDs. It will light up the LEDs in order.

The first block sets a variable (i) to zero. This variable will be used to count upwards from 1 to 7 (the pins on the shift register that we want to control. The clock pin (pin 1) and the latch pin (pin 2) are both set to zero.

 

The main loop contains a “for, do” block. It says that for our variable (i) having the values of 0 through to 7 will write to the following pins, with the values shown.

The data pin (pin 0) will be written to 8 times with the value of 0 through to 7 (corresponding to the data pins on the shift register.  Each time the data pin is written to, the value is stored in a memory area of the shift register.

For each value of i, the following sequence sets the clock pin from low to high (which reads the pin state data) and the latch pin from low to high which gets the data from the memory area and sends it to the output pin. The clock and latch pins are returned to zero ready for the next value of i. Finally, there is a pause of 2 seconds (2000ms) before I is incremented and the process begins again. Once the value of I equals 7, all LEDs will be on.

 

To see the LEDs light up again, the Micro Bit would have to be reset to start the program from the beginning. To avoid having to do that, the following program will light the LEDs in order and then turn them off in order. This process will be contained in a loop so it will run forever. The first block is the same as before.

 

The main block contains all of the pin writing commands which are in two separate “for, do” loops. I have added pauses at various points to make the sequences easier to follow.

 

Construct a program using the JavaScript Blocks editor. Download the program and upload the hex file onto the Micro Bit.

As the last LED in the sequence (LED number 7) lights up, LED number 0 switches off. This has something to do with the shift register that I don’t fully understand. This can be overcome by changing the first for i loop from “0 to 7” to “0 to 8”.

The 595 shift register is a very useful IC and can be used in numerous applications and projects.

Line Decoder SN74HCT138N 
The SN74HCT138N is a 3-to-8 line decoder/demultiplexer inverting. The 74HC138 / 74HCT138 decoders accept three binary weighted address inputs (A0, A1, A2) and when enabled, provide 8 mutually exclusive active LOW outputs (Y0 to Y7).

The 74HCT138N is a 3-to-8 DEMUX, Inverting. That means that it can turn 3 digital outputs into 8 digital outputs. Inverting means that the encoded output will actually be LOW, not HIGH as would be expected. That means that if you encode, for instance, a 4, the 4rd pin (Y3, as this is zero based) will be LOW while pins 0, 1, 2, 4, 5, 6 and 7 will be HIGH. For the purposes of this demonstration. Inverting and not Inverting are exactly the same.
 
Pinout
 

Truth table:
 

Connect the 74HCT138N to the Micro Bit as follows:

74HC138N Micro Bit
A0 P0
A1 P1
A2 P2
E3 P3
E1 GND
E2 GND
VCC 5V
GND GND
Y0-Y4 LED1 - 5

E1 and E2 are LOW (GND), therefore, E3 (connected to Arduino pin D5 is HIGH.


 

Construct a program like the one below using the JavaScript blocks editor. Install the resulting program on the Micro Bit.

By altering the program, you can achieve any sequence of the switching the LEDs on and off.
 





 
Multiplexer CD4051BE
The CD4051 is an analog multiplexer/demultiplexers and is a digitally controlled analog switch having low “ON” impedance and very low “OFF” leakage currents. .CD4051BC is a single 8-channel multiplexer having three binary control inputs. A, B, and C, and an inhibit input. 
 
To select a particular pin (y pin), you have to write to S0, S1 and S2 with values of either LOW or HIGH. The table below shows the values that should be written to address each of the y pins. 
Pin S0 S1 S2
y0 LOW LOW LOW
y1 HIGH LOW LOW
y2 LOW HIGH LOW
y3 HIGH HIGH LOW
y4 LOW LOW HIGH
y5 HIGH LOW HIGH
y6 LOW HIGH HIGH
y7 HIGH HIGH HIGH

Connect the Micro Bit to the CD4051BE via a solderless breadboard as follows:

CD4051BE Micro Bit
Pin 16 (Vcc) positive supply voltage 3V
Pin 6 (E) enable input (active LOW) GND
Pin 7 (Vee) negative supply voltage GND
Pin 8 (gnd) ground (0V) GND
Pin 11 (S0) Pin 0
Pin 10 (S1) Pin 1
Pin 9 (S2) Pin 2
Pin 3 (Z) Pin 10
y0-y7  (inputs/outputs) to potentiometers

To illustrate the selection of pins using the CD4051BE, connect eight potentiometers via a solderless breadboard to pins y0 to y7 of the multiplexer. We will be reading the values of the eight potentiometers using just 4 pins of the Micro Bit.

The following circuit diagram may look daunting but if you follow it closely and are patient, it is worth the effort.

 

I have constructed a simple program that will read the values of 8 potentiometers using the JavaScript Blocks Editor. 
We will need to write to Pins 0, 1 and 2 (HIGH or LOW for each pin) and read the analog value of a potentiometer (y pin). This value will then be displayed in the Serial Monitor of the Arduino IDE.
We will have to do this 8 times so that we can select each potentiometer (y pin) in turn and read and display the analog value.
Using the JavaScript Blocks Editor, we will need to set S0, S1 and S2 from above then read the value returned to pin 10. We will then serial print value of pin 10. After a short delay we will then repeat the whole process for all 8 potentiometers (y0 to y7).

The blocks below show this process for the first 2 potentiometers.  Note that the pin states “0” and “1” are used for writing “LOW” and “HIGH” to the CD4051BE.

 
After you have constructed the blocks for all 8 potentiometers, insert a serial write line instruction which will result in a new line for the next series of readings.
 
Save your program and upload it to the Micro Bit. Open the serial monitor of the Arduino programmer (if necessary change the baud rate to 115200). 
 

By altering each potentiometer, the individual numbers ion the serial monitor will change. You can see a graphical representation of the data by using the serial plotter but the Maker Plot package is far better for this,

 

Being able to read eight analog signals in by using so few pins, opens up a host of possibilities for potential applications. 
 
NE555 Frequency Adjustable Pulse Generator
The NE555 Frequency Adjustable Pulse Generator is a square wave pulse generator module based on the ubiquitous NE555 timer IC. The module can be powered from a wide power supply range (4.5 to 12V) and will produce a continuous square wave output between 15Hz to 24KHz which can be set by the on-board multi-turn potentiometer.

I the example below we will monitor the analog output whilst altering the on-board multi-turn potentiometer. Connect the module to the Micro Bit (GND to GND, VCC to VCC and output to pin P0).

Using the JavaScript blocks editor, construct the following program.

 

Save your program and upload it to the Micro Bit. Open the serial monitor of the Arduino programmer (if necessary change the baud rate to 115200). Alter the the on-board multi-turn potentiometer.and you will see the values change in the serial monitor.


By using a graphical program such as Maker Plot, the evidence that the output from the module is in fact a square wave pattern becomes evident.

 
Android & BBC Micro Bit 

Microcontrollers have come a long way and are being used more and more as technology finds new uses for them. The Micro Bit can be used in many applications and projects to collect/display data, communicate and drive components etc. Being able to do all this remotely would be very usesful and it is possible by using smart devices such as tablets and smart phones using Android apps.

What follows are examples that initially develop what’s been previously covered in this book and gives a basis for further development and integration of the Micro Bit and Android.

Android BLE Setup
The first step of building an Android app for the Micro Bit is to add the Bluetooth (BLE) extension to the App Inventor project. If you open the Extensions tab on the left hand side of App Inventor, there is an option to add an extension. Open this and there are options to either add from your computer or from a URL. At the tome of writing, the following link could be used: 

http://iot.appinventor.mit.edu/assets/resources/edu.mit.appinventor.ble.aix

I would advise that you search the internet for the latest BLE extension as these are updated regularly.

In the Design View, I constructed a screen which contains four buttons; Scan, Stop Scan, Connect and Disconnect. These are quite self-explanatory. The Status of the Bluetooth connection will be displayed in a label next to the Status label. The dark area is a list which I have called ListBLE. This will list all available Bluetooth devices once the Scan button is pressed. Below this I have a label “Data” and a corresponding label next to this to display data. These will be used later.

 

In the Blocks Editor, you can now set up the program for the app. The first thing to do is scan for available Bluetooth devices; in our case it should include our Micro Bit.

 

This part of the app will show a list of available Bluetooth devices.

 

When one can see the particular device in the list that they wish to connect to, they need to stop scanning. This is done by pressing the “Stop” button. The app will stop scanning and the status label text will display the message ”Stopped Scanning”

 

The user then selects the appropriate device from the list and presses the “Connect” button. The following block shows that the app will attempt to connect to the device and display a message in the message “Connecting” in the status label.

 

Once connected the status label will display “Connected”:

 

Pressing the “Disconnect” button results in the Bluetooth connection being terminated and the status label text being changed to “Disconnected”:

 

 

Save the project and download the apk. Install the app on your Android device and run it. 

This BLE setup will be used throughout the building of all of the Micro Bit Android apps that follow in this section.
Temperature Monitoring
After adding the Bluetooth (BLE) extension and necessary blocks to the App Inventor project (see Bluetooth Setup at the beginning of this Section), you will need to add the Micro Bit extension. If you open the Extensions tab on the left hand side of App Inventor, there is an option to add an extension. Open this and there are options to either add from your computer or from a URL. At the tome of writing, the following link could be used: 

http://iot.appinventor.mit.edu/assets/resources/com.bbc.microbit.profile.aix

I would advise that you search the internet for the latest BLE extension as these are updated regularly.

When connected, the following block firstly shows the status as “Connected”. The list of devices is no longer visible and the app requests temperature updates.

 

In the figure below, you can see that I have added a label “Data”. There is a corresponding label next to this which will display the temperature value from the Micro Bit.

 

In the Block view, you will need to construct a block that will tell the app what to do with the temperature data when it is received.

 

This block will display the temperature value between the words “Temperature: “ and “Degrees Centigrade” in the Data label. Eg:

Temperature: 25 Degrees Centigrade.

Save the project and download the apk. Install the app on your Android device and run it. You may need to pair your device with the Microbit first.

LED Control
Here we will send commands from the Android device to a Micro Bit to turn an LED on and off. Firstly you will need to set up an LED. This is most conveniently done using a solderless breadboard:

Attach the ground pin (shortest pin) to the ground pin of the Micro Bit. Attach the other (longer pin) if the LED to pin 0 (P0) of the Micro Bit via a 470 ohm resistor.



After adding the Bluetooth (BLE) extension and necessary blocks to the App Inventor project (see Bluetooth Setup at the beginning of this Section), you will need to add the Micro Bit extension. If you open the Extensions tab on the left hand side of App Inventor, there is an option to add an extension. Open this and there are options to either add from your computer or from a URL. At the time of writing, the following link could be used: 

http://iot.appinventor.mit.edu/assets/resources/com.bbc.microbit.profile.aix

I would advise that you search the internet for the latest BLE extension as these are updated regularly.

Using the Micro Bit block editor, you need to find the blocks associated with writing pin data. There are three types of pin data:

Here we are writing data to pin0 (the first number in each of the lists below.  Secondly we write either a “1” to turn on the LED or a “0” to turn the LED off..

 
 

The following App Inventor  emulator image shows the two buttons added to the interface,  one to turn the LED on and one to turn the LED off.

 

Save the project and download the apk. Install the app on your Android device and run it. You may need to pair your device with the Microbit first.

This project can be further developed to include more LEDs and, by adding more on and off buttons, you can control them all from an Android device.

Accelerometer

Firstly, you need to set up the Android app. The Bluetooth connection buttons and blocks described earlier can be reused. In the example below, I have included Start and Stop buttons, three labels for the accelerometer coordinates (x, y and z) and three labels for their corresponding values. Of course you can set up the screen to suit your own preferences. Notice the inclusion of the appropriate extensions.

 

Accelerometer App Design Screen Shot

Firstly, you will need to design the blocks for the buttons. Below I have programmed one to turn on the receiving of the accelerometer data and the other to turn off (or stop) data accelerometer updates.

 


 

Secondly you will need to decide what your app will do with the data that it receives. In this case we only need to display the data in the appropriate labels.

 

Save your project and download the apk file. Install the app on your Android device and run it.

As you move your Micro Bit in different directions and planes, you will see that the x, y and z coordinates on the Android change accordingly. The data changes rapidly so you could add some smoothing to your program to make it easier to follow.
Magnetometer 
Firstly, you need to set up the Android app. You can do this from scratch or modify one that you have made earlier for the accelerometer app. The Bluetooth connection buttons and blocks described earlier can be reused. In the example below, I have Start and Stop buttons, labels for the coordinates (x, y and z) and  labels for their corresponding values (as with the accelerometer example earlier).. I have added a label “Bearing” and a corresponding label to display the bearing value.

 

With all of the Bluetooth connection blocks in place, you should now build the blocks to turn the receiving of data from the Micro Bit on and off. These to blocks show how to do this for each of the buttons:

 

 

Once the buttons are set up, you now need to display the data. You will need to add the Magnetometer extension or use the blocks from the Micro Bit extension that contain the magnetometer blocks to your project. Using the following blocks, the data will be written to the corresponding labels.

 

 

Save your project, download the apk and install the app on your mobile device.

Before you connect to the Micro Bit, you need to calibrate the Micro Bit’s magnetometer. This simple program loaded onto the Micro Bit will begin by asking the user to draw a circle. This process will calibrate the magnetometer.

 

If you wish, you can add the following blocks to the program which will display the compass bearing on the Micro Bit every second (1000ms). This number is the number of degrees from north.

 

Once the hex file has been loaded and the magnetometer has been calibrated, you can now connect to the Micro Bit from the Android device. You will see that the x, y, z coordinates and the bearing are displayed on the Android device. Move the Micro Bit around and you will see the values received change.

 

No comments:

Post a Comment