Using NeoPixel LEDs with micro:bit
In this project we create some colourful patterns using a set of LEDs. These are special LEDs that can display a range of up to 16 million colours.
- A micro:bit
- An LED matrix such as the Kitronic ZIP Halo:
- A micro:bit battery pack
Connect your micro:bit
PeoPixel LED Code
Colours are defined using a system called RGB, which stands for Red, Green, Blue.
A colour is made by setting a value for red, blue and green, where each value is between 0 and 255, where 255 is the brightest. The number of possible combinations is more than 16 million.
For example, to create red, set a value for red but leave blue and green set to 0. So:
- red is 255, 0, 0 (bright)
- blue is 0,127, 0 (not so bright)
- green is 0, 0, 63 (even less bright)
Or combine colours, like these:
- Orange = 255, 127, 0
- Purple = 127, 0, 255
- Brown is 127, 63, 31
To test everything is working, type in this code.
One of the best ways to use LEDs is in loops. Here we’ve altered the code to set every LED to the same colour:
The range Function
Python’s range() function is a loop that makes a variable count up (or down). There are three ways to use the range() function.
The first just specifies how many times to count, one at a time, like this:
The second adds a starting number, like this:
Then we can also set the size of the count, like this:
We can use random numbers to generate different colours instead of just red. To do this we need to load an extra code library so that we can use random numbers. Add this near the top with the other import statements:
Now we can generate a colour by picking a random value for Red, Green and Blue. We’ll use three variables, one for each colour. Replace:
You should find that you get a different colour each time you reset the micro:bit.
To turn an LED off we set the colour to black. This is where there is no red, no green and no blue, like this:
To get a bright white light we can set all the colours to the maximum value of 255:
Using the same loop we can make it look like a colour is moving around the LEDs. The trick is turn off the previous LED before turning on the next one.
As we loop through each LED from 0 to 23 we can calculate the number of the previous LED because it will be one less than the current one. If we are about to turn on LED number 7 we know that the previous one was number 6:
When we are on the first LED, with number 0, we can use the last LED instead. This will be useful when we repeat the loop. We need to put all this into an if: