Using NeoPixel LEDs with micro:bit
- 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:
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:
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:
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: