As well as turning an LED on and off, you can also use it to control the brightness of the LED.

In this example, the A button will make the LED dimmer and the B button make it brighter. At the same time, the micro:bits built-in LED display will show a number between 0 and 9 indicating the brightness level.

# JavaScript Block Code

To open the JavaScript Block code in a separate tab, click here.

As you can see, there is actually quite a lot going on here. Lets start with the on start block. This block is run just once when the micro:bit starts and it defines four variables:

• min_power - the minimum output level for the LED when 0 is off and 1023 is maximum brightness
• max_power - the maximum output level for the LED. These two variable allow you to set the possible range of brightnesses.
• power_step - the brighness will be changed in 10 steps and so this value is calculated from the minumum and maximum.
• brightness - the brightness level as a number between 0 and 10.

The forever loop which runs repeatedly sets the value of a variable called power according to the brightness level.

To increase and decrease the brightness, two handlers are used. These respond to either a press of button A or button B and then display the brightness level and set the output level on pin0 using the analog write block.

# MicroPython

Here is the MicroPython code for the LED dimmer.

```from microbit import *

min_power = 50
max_power = 1023
power_step = (max_power - min_power) / 9
brightness = 0

def set_power(brightness):
display.show(str(brightness))
if brightness == 0:
pin0.write_analog(0)
else:
pin0.write_analog(brightness * power_step + min_power)

set_power(brightness)

while True:
if button_a.was_pressed():
brightness -= 1
if brightness < 0:
brightness = 0
set_power(brightness)
elif button_b.was_pressed():
brightness += 1
if brightness > 9:
brightness = 9
set_power(brightness)
sleep(100)```

# Arduino Code

The Arduino code for using the micro:bit's display is a little different because it uses the Adafruit GFX Library.

```#include <Adafruit_Microbit.h>

const int ledPin = 0;

const int minPower = 50;
const int maxPower = 255;
const int powerStep = (maxPower - minPower) / 9;

int brightness = 0;

void setup() {
pinMode(ledPin, OUTPUT);
microbit.begin();
pinMode(PIN_BUTTON_A, INPUT);
pinMode(PIN_BUTTON_B, INPUT);
setPower(brightness);
}

void loop() {
brightness --;
if (brightness < 0) {
brightness = 0;
}
setPower(brightness);
delay(200);
}
else if (digitalRead(PIN_BUTTON_B) == LOW) {
brightness ++;
if (brightness > 9) {
brightness = 9;
}
setPower(brightness);
delay(200);
}
}

void setPower(int brightness) {
microbit.print(brightness);
if (brightness == 0) {
analogWrite(ledPin, 0);
}
else {
analogWrite(ledPin, brightness * powerStep + minPower);
}
}```

This guide was first published on Mar 09, 2018. It was last updated on Mar 09, 2018.

This page (LED Brightness Control) was last updated on May 21, 2022.