LED Colours – learning RGB colours using micro:bit
In this project we set a special LED to a range of colours. Some LEDs can display more than just white light. Some can display a range of up to 16 million colours.
- A micro:bit
- An a colour LED on a board such as the Kitronic RGB LED:
- A micro:bit battery pack
- 4 coloured crocodile clip connectors
Connect your micro:bit
Plug the USB cable into USB socket on your computer so that you can flash you code onto the micro:bit.
Connect the 4 crodile clips to pins 0, 1, 2 and GND on the micro:bit.
Connect the other end to the red, green, blue and GND connectors on the LED board.
It doesn’t matter which colour cable you use but you must make sure they connect to the correct connector at each end. This is how it should look:
After the project is complete you can swap the USB cable for the battery pack to use it away from the computer.
RGB 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, which should show a blue light. Can you work out why?
- Try moving the 255 value to different pins. What colours do you get?
- Try increasing the value from 255. What happens?
- What happens if you set a value for more than one colour?
You are changing the depth of each of the three colours by changing the voltage applied to each pin.
The maximum value that you can use is 1023 for each colour.
Just as we did in the Pulse project, we can use the micro:bit’s sleep function to make the LED flash.
For example, we can make it flash between reg, green and blue using this code:
We are using a variable called pulse again to make it easier to change the ime between each colour.
See how we turn the LED off at end.
Using a function
Functions are good way to avoid repeating code over and over. Looking at the code above, we can simplify this by creating a function to set the three colours.
The functions has three arguments, one for each colour. We’ll use these when we call the function to set each of the three colours.
Can you make the LEDs flash in a continuous loop, like in the Pulse project?
Finally, we can use Pythons random number generator to create some random, flashing colours.
Note that we need to add some extra libraries at the top of the code to be able to use the random number functions.
Can you also make the time between each colour random too?