Program the RGB LED to show different colours by setting and mixing red, green and blue in the LED.
A light-emitting diode (LED) is a light source that emits light when electrical current flows through it. RGB LEDs (red green blue) contain three different LED emitters in one case. Each emitter can be controlled on it's own so together they can create different colours by mixing their colours.
In this project we will program the A, B and A+B buttons on our Microbit to control the level of red, green and blue that is shown.
First create a new Microbit project.
Go to the Makecode.com Microbit website using the link below and click on the 'New Project' button underneath the 'My Projects' heading.
Install the micro:bit app on your iPad or tablet.
Open the app, tap 'Create code' and then create a new project.
The RGB LED board has three channels, a red, a green and a blue channel. We can control the LED by setting a value for each of these channels and 'mix' a colour. We do this by using the analog write pin block.
To start create 3 variables that will store the level of red, green and blue that we will mix and show.
Once you have created the variables, add the following code to start them off at 0.
let red = 0 let green = 0 let blue = 0
In the Variables toolbox, create a new variable by clicking the 'Make a Variable' button.
Once you click this button a box will appear asking what you want to call your variable. Give it a name that reminds you what you will be using it for. For example, if you wanted to keep track of your score in a game, you would create a variable called 'score'.
Now let's program the A, B and A+B buttons to add 20 to variables each time you press the btton.
Add the following code.
input.onButtonPressed(Button.A, function () { red += 20 }) input.onButtonPressed(Button.AB, function () { blue += 20 }) input.onButtonPressed(Button.B, function () { green += 20 })
Now let's use the variables to write to the pins and mix the colour. Add the following code.
basic.forever(function () { pins.analogWritePin(AnalogPin.P0, red) pins.analogWritePin(AnalogPin.P1, green) pins.analogWritePin(AnalogPin.P2, blue) })
Give your project a name and send it to your Microbit by following these steps: