Microbit Inventor Project Sensors & Circuits
Normal
45 mins
160 points
What you need:
• Computer/laptop
• Microbit
• RGB LED

# RGB Colour Mixer

Program the RGB LED to show different colours by setting and mixing red, green and blue in the LED.

### 1 - Create a new Microbit project

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.

### 2 - Create 3 variables

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.

• Pin 0 (P0) is the red channel (min 0 max 1023).
• Pin 1 (P1) is the green channel (min 0 max 1023).
• Pin 2 (P2) is the blue channel (min 0 max 1023).

To start create 3 variables that will store the level of red, green and blue that we will mix and show.

1. red - this will store the level of red.
2. green - this will store the level of green.
3. blue - this will store the level of blue.

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

```

### 3 - Increase their values

Now let's program the A, B and A+B buttons to add 20 to variables each time you press the btton.

• The A button will add 20 to the red variable.
• The B button will add 20 to the green variable.
• The A+B buttons will add 20 to the blue variable.

```input.onButtonPressed(Button.A, function () {
red += 20
})
input.onButtonPressed(Button.AB, function () {
blue += 20
})
input.onButtonPressed(Button.B, function () {
green += 20
})

```

### 4 - Mix the colours

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)
})

``` 