Lesson 3 – Micro:bit Accelerometer
In Lesson 3 we looked at all the different ways that the micro:bit could be used to measure acceleration. We watched a short video of a Formula 1 car as it went around a race circuit with a display showing the amount of G-force the driver was experiencing and the direction the force was applied in.
The micro:bit provides a number of different ways to use the accelerometer data:
In this lesson we will look at ways to use the pitch and roll blocks to control a pixel on the screen. We started with the following code:
This code creates a sprite (dot) in the centre of the display. The while loop then runs forever, checking the pitch and roll of the microbit. Here, if the roll is more than 10 degrees then 1 is added to the x (horizontal) position of the sprite. The sprite (from the game menu) lets us move the dot simply by using the ‘change sprite’ block & will also be useful at the end of the lesson when we want to detect if two sprites (dots) are touching!
We can then duplicate the IF block and add in statements for the other directions:
We compiled this code and tested it on our micro:bit’s. We then added a couple of extra blocks to make it into a game!
The first few lines start a game countdown of ten seconds, and the second positions another sprite (goal) randomly on the screen. The final block (IF) is added to the end of the code after the last IF statement and it uses the ‘touching’ block from the game menu to tell if the two sprites are on top of each other. If they are, your score is increased by 1 and the ‘goal’ sprite then moves to another random location.
If you’d like to try the game or take a look at the final code you can download it here.