C++ on the micro:bit v2 using Codal
Last updated: Dec 8, 2023
C++ on the micro:bit v2 using Codal
Note: These instructions are valid for the micro:bit v2, not the micro:bit v1.
Summary
Using Codal we can write code for the micro:bit v2 in C++.
How to use the examples
- Clone the Codal GitHub repository.
- Edit the sample file sample/main.cpp
- Build the project using the command ./build.py - you might need to type
python3 build.py
- Copy the new MICROBIT.hex file onto your micro:bit v2.
Note: This won’t work with a micro:bit v1.
On your first build, a bunch of files are copied and updated from GitHub into the cloned repository. Subsequent builds do not do this.
To clean a previous build - that is delete previously created build files - run ./build.py -c. If you’re getting unexpected and unexplained behaviour building a project, it is worth running a build with the clean option.
If you build the sample project without changing the main.cpp file, you get the ‘out of the box’ hex file created, which is the noisy demo program put onto new micro:bits. Which gets annoying when you’re working with micro:bits at 2am in the morning, trying to get something working to an unreasonable deadline.
How to run a different sample
Look in the file Tests.h. in the directory source/samples. You will see a list of all of the sample programs that can be built. These are all in the .cpp files in the same directory. For instance, let’s build and run the demo program spirit_level1(). The listing for this function can be found in the file AccelerometerTest.cpp.
Edit the file main.cpp in the directory /source to be:
#include "samples/Tests.h"
MicroBit uBit;
int main()
{
uBit.init();
spirit_level();
// microbit_panic( 999 );
}
You don’t need to comment out the last line microbit_panic ( 999 ), but I’m not sure what it does, so I knocked it out. I’d like to know what it does. Let me know if in the comments if you know.
Build the new sample file by running ./build.py from the top directory of the samples. You might need to type:
python3 build.py
Now connect your micro:bit and copy the newly created MICROBIT.hex file to it. You should see a single pixel on the micro:bit that moves around as you tilt the micro:bit around.
Comparison with micro:bit v1 build
The build process using Codal seems faster and with fewer levels of abstraction than used with the C++ build system used with micro:bit v1. For instance, yotta is no longer used. I tried to get my head around the stack of abstraction layers for the C++ build system used with micro:bit v1 a few years ago in this post.
Final thoughts
The samples give us something to build on. Pretty much all systems I’ve worked on include Python3, so having the build script written in Python doesn’t require a new dependency to be added to most systems. The Makefile used in the final build can be found in the directory /build.