Spirit Level

Coding is a process. It starts by thinking about what you want to accomplish. Then figuring out how you will do it. Then putting the code together. And finally, testing it.

What are we trying to do?

We need to think about what a spirit level does. It shows when something is level by having a bubble in the middle of the little window. If the left hand side of the level is too high the bubble goes to the left. If the right hand side of the level is too high the bubble goes to the right.

Next we need to decide what will be 'the bubble' in our microbit spirit level? A good choice would be to light up one of the LEDs.

To light up an LED we use the plot block. It takes two parameters: x - how far across the set of LEDS and y - how far from the top to the bottom. The positions of the LEDs are numbered as in the picture. The (x,y) values of the LED where the O is in the picture is (3,2)

Next we need to know what information does the accelerometer give us? This is where you might need to write a little program just to find this out. For now I will just tell you the answer: The x value is 1023 when the left side of the microbit is tilted upwards. Then it gradually goes down to 0 when the microbit is horizontal. Then it gets more and more negative as the right hand side of the microbit goes up. It stops going up when it gets to -1023.


                    0   1   2   3   4

                0   *   *   *   *   *

                1   *   *   *   *   *

                2   *   *   *   O   *

                3   *   *   *   *   *

                4   *   *   *   *   *    
            

So we have a lot of numbers, from 1023 to -1023, but only 5 LEDs. We need to divide our set of numbers into five sections. To do this we will create a list of numbers. Then we will find out how much the microbit is tilted. This tilt fits somewhere in between the numbers in our list. We can find out where in the list it fits by using a 'for' block and a 'greater than' block. Here is a good set of numbers to use.

01234
51250-50-512-1024

It takes a bit of trial and error to find the best numbers to use.

Now we write some code. I put most of the code in a block I made myself. I called my block 'x level'. In the main part of the program I call the block. Then I put a pause so you have time to see which LED is lit up. Then I clear the screen. Now, when it loops round, we don't end up with lots of LEDs all lit up!

Finally, when all the code was tested and working, I copied my 'x level' block, renamed it to 'y level', made a few changes and now the code shows when the microbit is tipping forward or backwards.

One last detail: the break block jumps out of a loop. We are using this here because when the code has lit up an LED there is nothing else to do so it can just jump out of the loop. There is nothing else to do in the x level and y level functions so they just end and the microbit continues running the main program.