C/C++ coding tutorial - bitty data_logger

micro:bit code

Bitty Data Logger can capture and chart accelerometer, magnetometer and temperature data, streamed live from your micro:bit. The code we need to wrote for the micro:bit is actually very, very simple.

All we need the micro:bit to do is to provide a visual indication of whether or not it has a Bluetooth connection and to activate the Bluetooth accelerometer, magnetometer and temperature "services", which are software components responsible for making accelerometer, magnetometer and temperature data available over Bluetooth.

As with all our apps you can simply download and install a hex file which we've prepared for you or you can code it yourself, following the Bitty Software coding tutorial below. Naturally, we recommend you code it yourself!

before you start

To program your micro:bit using C/C++ you need the Yotta tools and the micro:bit 'DAL' source code on a PC or Mac. If you haven't yet set this environment up, read the information on our tools page and make sure you can build and install the Hello World sample code onto your micro:bit before going any further. If you've accomplished this then you have a working C/C++ environment for micro:bit development and can move on.

You should also install the bitty data logger application on your phone so you can use it for testing whilst you develop the micro:bit code. Check the bitty data_logger page for details of where to find the app for your type of phone or tablet.

step 1 - set up initial source code files

Download our project starter source code file to your microbit-samples\source folder. Delete any ".cpp" files you already had there. Rename the file to DataLogger.cpp so it has a name that reflects what it does.

During the course of the tutorial, you'll create a micro:bit hex file which does not require Bluetooth pairing. At the end of the tutorial, when everything is working, we'll do one final build that does need your phone or tablet to pair with your micro:bit so that nobody else can connect to your micro:bit.

Download this config.json file and save it in your microbit-samples folder. Rename it to config.json.

Your microbit-samples folder should now look like this:

And your microbit-samples source folder should look like this:

config.json includes various build properties that affects certain aspects of your micro:bit hex file once you have created it:

The property "open" which has a value of "1" means that your micro:bit will not need to be paired with your phone to be usable. This makes life easier during development but before you finish your project, remember to review this and if you decide you do want security then change the property to "0" and build again. You'll now need to pair your micro:bit with your phone.

Open DataLogger.cpp in a text editor.

The lines which start with "//" are comments which are there to help you understand the code. Review them now. Don't worry if the final comment block about fibers makes no sense to you at this stage. The key point here is that when programming a micro:bit, finishing with a call to the release_fiber() function is good practice.

step 2 - change the start-up message

To get things started let's just change the start-up message which is displayed on the micro:bit to something more fitting. Change it to "DATA" now and save your text file.

// Display a start-up message

Your code should now look very similar to this:

step 3 - build and test

If you haven't already done so, find and launch the "Run Yotta" shortcut that should have been created for you when you installed Yotta. This will result in a window you can type commands into appearing. Use 'cd' to navigate to your microbit-samples folder.

Your micro:bit does not process C/C++ code directly. We have to translate it into a binary format which the micro:bit understands using a process called "building". Before we go any further, let's build and install your application now to make sure everything is working as expected. Follow the steps for building and installing your code and then return here and continue.

Tip: It's a good idea to progress by making small changes, building and testing at each step rather than typing huge amounts of code and then trying to build and test all in one go. It's much easier to solve problems when we're only making small changes each time.

Press the reset button on the back of your micro:bit. Your code will execute and you should see the text "DATA" scroll across the LED display.

step 4 - keeping track of the bluetooth connection state

bitty data logger uses Bluetooth for communication between the micro:bit and mobile app. Before any communication can take place, the mobile device must connect to the micro:bit. Our micro:bit code needs to keep track of whether or not something is connected by Bluetooth to it and and indicate this status to the user in a simple way using the LED.

Read all about keeping track of Bluetooth connections now and then come back here to resume the tutorial.

Change your code and include event handlers for responding to changes in the Bluetooth connection state as shown below.

void onConnected(MicroBitEvent)

void onDisconnected(MicroBitEvent)
In the main() function you should also have:
// Application code will go here and in functions outside of main()
uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_CONNECTED, onConnected);
uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_DISCONNECTED, onDisconnected);   

step 5 - Activate the Bluetooth services

The BBC micro:bit is equipped with extensive Bluetooth capabilities. Think of any given feature of the micro:bit and there's a good chance you can use it over Bluetooth. This is made possible through the micro:bit having a custom Bluetooth "profile" designed for it. The profile includes a variety of "services", each of which is responsible for Bluetooth use of a given aspect of the micro:bit. If you'd like a better understanding of the terms and concepts relating to Bluetooth, read this article from the Bluetooth SIG's blog.

The Bluetooth services we want to use need to be explicitly added to our code so that when the micro:bit starts up, the services are activated. We just need the accelerometer, magnetometer and temperature services, so add the following lines of code to your main function:

    new MicroBitAccelerometerService(*uBit.ble, uBit.accelerometer);
    new MicroBitMagnetometerService(*uBit.ble, uBit.compass);
    new MicroBitTemperatureService(*uBit.ble, uBit.thermometer);

Full details of the micro:bit's Bluetooth capabilities are documented at the Lancaster University web site.

step 6 - test

Believe it or not, that's all the code that is needed to make micro:bit accelerometer data available to your phone over Bluetooth! It really is that easy! So, if all has gone to plan, we should now have a completed micro:bit application for use with the bitty data logger application. Build and install your hex file onto your micro:bit in preparation for testing.

Immediately after installing your hex file, you will be prompted to "draw a circle" by a message which scrolls across the display. Hold your micro:bit so that the display is oriented in the vertical plane and then slowly rotate it through 360 degrees. You should see a single LED pixel lit and it should move to the bottom of the display with respect to gravity. This strange process involves collecting both data about magnetic fields in the local environment and motion and results in your micro:bit being properly calibrated for use in that environment.

The magnetometer may generate strange looking data if used in an environment other than that in which the calibration procedure was performed. Motion may also affect magnetometer data. For best results, always reinstall the hex file and recalibrate in any environment in which you want to capture magnetometer data.

Now test with the Bitty Data Logger application on your phone to make sure everything is working.

If Bitty Data Logger reports that you do not have one of the required Bluetooth services on your micro:bit, there are two possibilities. Either you really do not have this service activated, in which case there's an issue with your code or.... you do but your phone is looking at old, cached details associated with your micro:bit from some previous time the two have been used together. If you suspect the latter, try using the "Refresh Services" feature of the nRF Connect application which is recommended from the tools page. Make sure your micro:bit is not listed by your phone as a paired device as well. Right now it shouldn't be paired if you've been following the tutorial. If necessary, "forget" the device from the paired devices list. Switching Bluetooth off and on again may help. If after a reboot of your phone, Bitty Data Logger is still saying the accelerometer service is not on your phone then it probably isn't!


step 7 - make Bluetooth pairing required

For this application it makes sense to use Bluetooth pairing. If you pair your micro:bit with your phone then nobody else will be able to connect to your micro:bit.

Edit the config.json file in your microbit-samples folder and change it so that the 'open' property is set to 0 and the 'pairing_mode' property is set to 1, as shown here:

    "microbit-dal": {
        "bluetooth": {
            "enabled": 1,
            "pairing_mode": 1,
            "private_addressing": 0,
            "open": 0,
            "whitelist": 1,
            "advertising_timeout": 0,
            "tx_power": 6,
            "dfu_service": 0,
            "event_service": 1,
            "device_info_service": 1
        "gatt_table_size": "0x600"

Run 'yt clean' and then 'yt build' to rebuild your application in full and install the hex file on your micro:bit.

you've finished!

That's it! You've finished and are all set to have fun with the bitty data logger application. You've also learned about Bluetooth connection trackingand how to activate the Bluetooth accelerometer service on your micro:bit. Congratulations!

if you get stuck

Check the steps above carefully and see if you can spot where things have gone wrong. If necessary, start again and proceed very slowly. building and testing at each step. Take a look at the solution and compare the code with yours.

If you did not install the correct config.json file in the microbit-samples directory or put it in the wrong place (e.g. in microbit-samples/source) then the app may not work because the pairing settings on the phone compared with the micro:bit may not match. Check the location and content of config.json. Try pairing your phone with your micro:bit. See our list of common issues for more information on this.

Make sure no other app on your phone is connected to your micro:bit. If you've been experimenting with other apps like nRF Connect, for example, this can easily happen. List the running apps on your phone and kill any that use Bluetooth, just to be sure. Kill and restart the bitty data logger app too.