# micro:bit Lesson 2. Controlling LEDs on Breadboard

## Overview

In this lesson, you will learn how to connect a micro:bit to solderless breadboard and how to turn an LED on and off, control its brightness and also use three LEDs to make a traffic signal.

![](https://cdn-learn.adafruit.com/assets/assets/000/049/883/medium800thumb/leds_traffic.jpg?1515316418)

You will start off just making a single LED blink, then control the brightness of the LED and finally add two more LEDs to make the traffic signal shown above.

# micro:bit Lesson 2. Controlling LEDs on Breadboard

## Parts

To follow all the activities in this lesson, you will need the following parts. You will also need a micro USB lead to connect your micro:bit to your computer.

Featured
### Half Sized Premium Breadboard - 400 Tie Points

[Half Sized Premium Breadboard - 400 Tie Points](https://www.adafruit.com/product/64)
This is a cute, half-size breadboard with&nbsp;400 tie points, good for small projects. It's 3.25" x 2.2" / 8.3cm&nbsp;x 5.5cm&nbsp;with a standard double-strip in the middle and two power rails on both sides.&nbsp;You can pull the power rails off easily to make the breadboard as...

In Stock
[Buy Now](https://www.adafruit.com/product/64)
[Related Guides to the Product](https://learn.adafruit.com/products/64/guides)
![Angled shot of half-size solderless breadboard with red and black power lines.](https://cdn-shop.adafruit.com/640x480/64-06.jpg)

Featured
### Small Alligator Clip to Male Jumper Wire Bundle - 12 Pieces

[Small Alligator Clip to Male Jumper Wire Bundle - 12 Pieces](https://www.adafruit.com/product/3255)
For bread-boarding with unusual non-header-friendly surfaces, these cables will be your best friends! No longer will you have long strands of alligator clips that are grabbing little wires. These compact jumper cables have a premium male header on one end, and a grippy mini alligator clip on...

In Stock
[Buy Now](https://www.adafruit.com/product/3255)
[Related Guides to the Product](https://learn.adafruit.com/products/3255/guides)
![ Bundle of Small Alligator Clip to Male Jumper Wires](https://cdn-shop.adafruit.com/640x480/3255-02.jpg)

Featured
### Super Bright Red 5mm LED (25 pack)

[Super Bright Red 5mm LED (25 pack)](https://www.adafruit.com/product/297)
Need some really bright LEDs? We are big fans of these clear red LEDs, in fact we use them exclusively in our kits. They are very bright and have about 20degree LED beam. They go easily into a breadboard and will add that extra zing to your project.

- Pack of 25 clear red...

In Stock
[Buy Now](https://www.adafruit.com/product/297)
[Related Guides to the Product](https://learn.adafruit.com/products/297/guides)
![Single LED lit up red - 5mm.](https://cdn-shop.adafruit.com/640x480/297-00.jpg)

Featured
### Super Bright Yellow 5mm LED (25 pack)

[Super Bright Yellow 5mm LED (25 pack)](https://www.adafruit.com/product/2700)
Need some really bright LEDs? We are big fans of these clear yellow LEDs, in fact we use them exclusively in our kits. They are very bright!&nbsp;They go easily into a breadboard and will add that extra zing to your project.

**This comes in a pack of 25!**

<a...></a...>

In Stock
[Buy Now](https://www.adafruit.com/product/2700)
[Related Guides to the Product](https://learn.adafruit.com/products/2700/guides)
![Single LED lit up bright yellow](https://cdn-shop.adafruit.com/640x480/2700-00.jpg)

Featured
### Super Bright Green 5mm LED (25 pack)

[Super Bright Green 5mm LED (25 pack)](https://www.adafruit.com/product/300)
Need some really bright LEDs? We are big fans of these clear green LEDs, in fact we use them exclusively in our kits. They are very bright and have about 20degree LED beam. They go easily into a breadboard and will add that extra zing to your project.

- Pack of 25 clear green...

In Stock
[Buy Now](https://www.adafruit.com/product/300)
[Related Guides to the Product](https://learn.adafruit.com/products/300/guides)
![Single LED lit up bright green](https://cdn-shop.adafruit.com/640x480/300-00.jpg)

Featured
### Through-Hole Resistors - 470 ohm 5% 1/4W - Pack of 25

[Through-Hole Resistors - 470 ohm 5% 1/4W - Pack of 25](https://www.adafruit.com/product/2781)
ΩMG! You're not going to be able to resist these handy resistor packs!&nbsp;Well, axially, they&nbsp;do all of the resisting for you!

This is a **25 Pack of 470Ω Resistors.** More specifically, they are **carbon film** , through-hole...

In Stock
[Buy Now](https://www.adafruit.com/product/2781)
[Related Guides to the Product](https://learn.adafruit.com/products/2781/guides)
![Angled shot of 25 Through-Hole Resistors - 470 ohm 5% 1/4W.](https://cdn-shop.adafruit.com/640x480/2781-00.jpg)

# micro:bit Lesson 2. Controlling LEDs on Breadboard

## Breadboard Layout

Connect the resistor and LED as shown in the diagram below. Make sure that the longer lead of the LED (the positive lead) is to the left. It doesn't matter which way around the resistor goes.

![](https://cdn-learn.adafruit.com/assets/assets/000/049/858/medium800/leds_breadboard_blink.png?1515194434)

When connecting the micro:bit to the breadboard, its best to put the alligator clips vertically into the holes on the micro:bit's pads, otherwise the clips can slip off or make accidental connections with neighbouring connectors on the micro:bit.

The way that solderless breadboard works is that behind the holes into which you poke component leads you will find a metal clip.&nbsp;

The red lead that connects pin0 on your micro:bit to row 3 of the breadboard actually connects the lead to every hole position on that row (at least for the left-hand bank of rows of five). The right-hand side of the resistor then connects to the clip underneath row 3 on the right-hand bank and hence to the positive lead of the LED.

The long columns down the sides of the breadboard work differently from the main rows of connections in the central area of the breadboard. Each of these long columns are bade up of a single long clip that is often used to provide power. In this case the right hand column (with a blue line next to it) is connected to the micro:bit's GND connection and also to the negative side of the LED.

The resistor is necessary to limit the current flowing through the LED. A digital output from a micro:bit should not be allowed to draw more than 3mA of current. The 470Ω resistor limits the LED current to under the 3mA limit.&nbsp;

# micro:bit Lesson 2. Controlling LEDs on Breadboard

## Blinking an LED

![](https://cdn-learn.adafruit.com/assets/assets/000/049/859/medium800thumb/leds_blink.jpg?1515220712)

Lets start by making our LED blink on and off. The way to make an LED blink is to follow this sequence of code instructions over and over again:

- Turn the LED on

- Delay for a period of time

- Turn the LED off

- Delay for a period of time

The code for this is different depending on which programming platform you have chosen to use.

# JavaScript Block Code

The JavaScript Blocks Code editor is embedded directly on this page below. From the editor, you can click on Download button (bottom right) and then copy the downloaded file onto your micro:bit. Alternatively, you can [Click here](https://makecode.microbit.org/_HeX6RUfM7d1h)&nbsp;to open the editor in a separate browser tab.

https://makecode.com/_HeX6RUfM7d1h

To install the program, copy the hex file onto your micro:bit. See [this guide](../../../../bbc-micro-bit-lesson-number-0/javascript-blocks-editor) for getting started with Javascript Blocks.

The _Forever_ block will repeatedly run all the code contained in the block.

&nbsp;

# MicroPython

To run the MicroPython version of the code, open up the [online Python editor here](http://python.microbit.org/)&nbsp;and paste the following code into the editor window.

```auto
from microbit import *

while True: 
    pin0.write_digital(1)  # turn pin0 (and the LED) on
    sleep(500)             # delay for half a second (500 milliseconds)
    pin0.write_digital(0)  # turn pin0 (and the LED) off
    sleep(500)             # delay for half a second
```

The program first imports the _microbit_ library that contains the _write\_digital_ function needed to control the pins on and off.

The _while_ loop will repeat the commands it contains until you unplug your micro:bit. These commands first turn the pin on, delay for half a second, turn it off again and then delay again.

&nbsp;

# Arduino

Make sure that you have your Arduino environment set up for micro:bit by following [this guide](../../../../use-micro-bit-with-arduino/overview).

Now start a new Sketch by clicking on the _File_ menu and _New_. Then paste the following code into the editor window.

```auto
// define a constant for the LED pin
const int ledPin = 0;

// setup is run just once when the micro:bit starts up
void setup() {
  pinMode(ledPin, OUTPUT);    // set the ledPin (pin0) to be an output
}

void loop() {
  digitalWrite(ledPin, HIGH); // turn the ledPin (and LED) on
  delay(500);                 // delay for half a second (500 milliseconds)
  digitalWrite(ledPin, LOW);  // turn the ledPin (and LED) off
  delay(500);                 // delay for half a second
}
```

Save the file and then upload it onto your micro:bit.

The Arduino version of the code is slightly different from MicroPython and the JavaScript Blocks code, because when using an Arduino you have to specify that the pin is to act as an output, whereas for the other languages this happens automatically the first time you use the pin as an output.

# micro:bit Lesson 2. Controlling LEDs on Breadboard

## Traffic Signal

![](https://cdn-learn.adafruit.com/assets/assets/000/049/896/medium800thumb/leds_traffic.jpg?1515363918)

This example uses three LEDs to make a model traffic light signal. You can use all red LEDs if you like, but its more realistic if you use red, yellow and green.

The LEDs cycle around in the sequence red, yellow, green, yellow and then back to red again.

To add the extra LEDs and resistors, wire them up as shown in the breadboard layout below.

![](https://cdn-learn.adafruit.com/assets/assets/000/049/884/medium800/leds_new_traffic_breadboard.png?1515335833)

Take care to ensure that the LEDs are the right way around, with the longer positive leads (anodes) to the left.

# JavaScript Blocks Code

The JavaScript Blocks Code editor is embedded directly on this page below. From the editor, you can click on Download button (bottom right) and then copy the downloaded file onto your micro:bit. Alternatively, you can [Click here](https://makecode.microbit.org/_1h17m4Mx2VxL) to open the editor in a separate browser tab.

https://makecode.com/_7ko72D3X7Ka0

# MicroPython Code

The MicroPython code is listed below.

```auto
from microbit import *

red_pin = pin0    # giving the LED pins names by using variables
amber_pin = pin1  # makes it easier to see how the program works
green_pin = pin2

while True: 
    # red - turn amber LED off and red LED on
    amber_pin.write_digital(0)
    red_pin.write_digital(1)
    sleep(4000) # delay 4 seconds
    # amber - turn red LED off and amber LED on
    red_pin.write_digital(0)
    amber_pin.write_digital(1)
    sleep(1000)
    # green - turn amber LED off and green LED on
    amber_pin.write_digital(0)
    green_pin.write_digital(1)
    sleep(4000)
    # amber - turn green LED off and amber LED on
    green_pin.write_digital(0)
    amber_pin.write_digital(1)
    sleep(1000)
```

# Arduino code

The Arduino version of this program is very similar to the other two versions.

```auto
// define constants for each LED pin
const int redPin = 0;
const int amberPin = 1;
const int greenPin = 2;

void setup() {
  // set all three pins to act as digital outputs
  pinMode(redPin, OUTPUT);
  pinMode(amberPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
}

void loop() {
    // red - turn amber LED off and red LED on
    digitalWrite(amberPin, LOW);
    digitalWrite(redPin, HIGH);
    delay(4000);   // delay 4 seconds
    // amber - turn red LED off and amber LED on
    digitalWrite(redPin, LOW);
    digitalWrite(amberPin, HIGH);
    delay(1000);
    // green - turn amber LED off and green LED on
    digitalWrite(amberPin, LOW);
    digitalWrite(greenPin, HIGH);
    delay(4000);
    // amber - turn green LED off and amber LED on
    digitalWrite(greenPin, LOW);
    digitalWrite(amberPin, HIGH);
    delay(1000);
}
```

# micro:bit Lesson 2. Controlling LEDs on Breadboard

## LED Brightness Control

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.

![](https://cdn-learn.adafruit.com/assets/assets/000/049/945/medium800thumb/leds_brightness.jpg?1515404379)

# JavaScript Block Code

To open the JavaScript Block code in a separate tab, [click here](https://makecode.microbit.org/_EeoaEMcXoA5o).

![](https://cdn-learn.adafruit.com/assets/assets/000/049/864/medium800/leds_brightness_block_code.png?1515224365)

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.&nbsp;
- 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.

```auto
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](../../../../adafruit-gfx-graphics-library).

```auto
#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;
Adafruit_Microbit_Matrix microbit;

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

void loop() {
  if (digitalRead(PIN_BUTTON_A) == LOW) {
    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);
  }
}
```

# micro:bit Lesson 2. Controlling LEDs on Breadboard

## Other Things to Do

Using whatever programming language for the micro:bit that you like best, try modifying the _blink_ or _traffic signal_ code to change the timing of the LEDs.&nbsp;

For the traffic signal project, you could also try changing the code so that it behaves like a pedestrian crossing and the lights change in response to you pressing button A.

&nbsp;

# About the Author

If you have found this lesson useful, and want to learn Python, then you might like my book Programming the BBC micro:bit: Getting Started with MicroPython.&nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/049/944/medium800/leds_cover.jpg?1515403493)


## Guide Products

### BBC micro:bit

[BBC micro:bit](https://www.adafruit.com/product/3530)
The British Invasion is here! No, not music...microcontrollers! New to the USA is the newest and _easiest_ way to learn programming and electronics - the **BBC micro:bit**.

Designed specifically for kids and beginners, the&nbsp; **micro:bit** &nbsp;is a...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/3530)
[Related Guides to the Product](https://learn.adafruit.com/products/3530/guides)
### Half Sized Premium Breadboard - 400 Tie Points

[Half Sized Premium Breadboard - 400 Tie Points](https://www.adafruit.com/product/64)
This is a cute, half-size breadboard with&nbsp;400 tie points, good for small projects. It's 3.25" x 2.2" / 8.3cm&nbsp;x 5.5cm&nbsp;with a standard double-strip in the middle and two power rails on both sides.&nbsp;You can pull the power rails off easily to make the breadboard as...

In Stock
[Buy Now](https://www.adafruit.com/product/64)
[Related Guides to the Product](https://learn.adafruit.com/products/64/guides)
### Small Alligator Clip to Male Jumper Wire Bundle - 12 Pieces

[Small Alligator Clip to Male Jumper Wire Bundle - 12 Pieces](https://www.adafruit.com/product/3255)
For bread-boarding with unusual non-header-friendly surfaces, these cables will be your best friends! No longer will you have long strands of alligator clips that are grabbing little wires. These compact jumper cables have a premium male header on one end, and a grippy mini alligator clip on...

In Stock
[Buy Now](https://www.adafruit.com/product/3255)
[Related Guides to the Product](https://learn.adafruit.com/products/3255/guides)
### Super Bright Red 5mm LED (25 pack)

[Super Bright Red 5mm LED (25 pack)](https://www.adafruit.com/product/297)
Need some really bright LEDs? We are big fans of these clear red LEDs, in fact we use them exclusively in our kits. They are very bright and have about 20degree LED beam. They go easily into a breadboard and will add that extra zing to your project.

- Pack of 25 clear red...

In Stock
[Buy Now](https://www.adafruit.com/product/297)
[Related Guides to the Product](https://learn.adafruit.com/products/297/guides)
### Super Bright Yellow 5mm LED (25 pack)

[Super Bright Yellow 5mm LED (25 pack)](https://www.adafruit.com/product/2700)
Need some really bright LEDs? We are big fans of these clear yellow LEDs, in fact we use them exclusively in our kits. They are very bright!&nbsp;They go easily into a breadboard and will add that extra zing to your project.

**This comes in a pack of 25!**

<a...></a...>

In Stock
[Buy Now](https://www.adafruit.com/product/2700)
[Related Guides to the Product](https://learn.adafruit.com/products/2700/guides)
### Super Bright Green 5mm LED (25 pack)

[Super Bright Green 5mm LED (25 pack)](https://www.adafruit.com/product/300)
Need some really bright LEDs? We are big fans of these clear green LEDs, in fact we use them exclusively in our kits. They are very bright and have about 20degree LED beam. They go easily into a breadboard and will add that extra zing to your project.

- Pack of 25 clear green...

In Stock
[Buy Now](https://www.adafruit.com/product/300)
[Related Guides to the Product](https://learn.adafruit.com/products/300/guides)
### Through-Hole Resistors - 470 ohm 5% 1/4W - Pack of 25

[Through-Hole Resistors - 470 ohm 5% 1/4W - Pack of 25](https://www.adafruit.com/product/2781)
ΩMG! You're not going to be able to resist these handy resistor packs!&nbsp;Well, axially, they&nbsp;do all of the resisting for you!

This is a **25 Pack of 470Ω Resistors.** More specifically, they are **carbon film** , through-hole...

In Stock
[Buy Now](https://www.adafruit.com/product/2781)
[Related Guides to the Product](https://learn.adafruit.com/products/2781/guides)

## Related Guides

- [Micro:bit Radio Control of Crickit Robotics](https://learn.adafruit.com/micro-bit-radio-control-of-crickit-robotics.md)
- [Micro:Bit Puppet "Text Message" System!](https://learn.adafruit.com/micro-bit-radio-controlled-puppet.md)
- [Compost Friend!](https://learn.adafruit.com/compost-optimization-machine.md)
- [CircuitPython Libraries on Linux and the 96Boards DragonBoard 410c](https://learn.adafruit.com/circuitpython-libraries-on-linux-and-the-96boards-dragonboard-410c.md)
- [micro:bit Lesson 3. NeoPixels with micro:bit](https://learn.adafruit.com/micro-bit-lesson-3-neopixels-with-micro-bit.md)
- [CircuitPython Libraries on Linux and Orange Pi](https://learn.adafruit.com/circuitpython-on-orangepi-linux.md)
- [PyPortal IoT Weather Station](https://learn.adafruit.com/pyportal-iot-weather-station.md)
- [Comparison and Experimentation with Flammable Gas Sensors](https://learn.adafruit.com/gas-sensor-comparison.md)
- [Adafruit IO Home: Lights and Temperature ](https://learn.adafruit.com/adafruit-io-house-lights-and-temperature.md)
- [Adafruit IO Home: Security ](https://learn.adafruit.com/adafruit-io-home-security.md)
- [Using micro:bit and CRICKIT with MicroPython](https://learn.adafruit.com/using-micro-bit-and-crickit-with-micropython.md)
- [Working with Multiple Same Address I2C Devices](https://learn.adafruit.com/working-with-multiple-i2c-devices.md)
- [FruitBox Sequencer: Musically Delicious Step Pattern Generator ](https://learn.adafruit.com/circuitpython-fruitbox-sequencer-musically-delicious-step-pattern-generator.md)
- [Makey Paper Craft ](https://learn.adafruit.com/makey-paper-craft.md)
- [Motorized Grinch Fireplace](https://learn.adafruit.com/grinch-fireplace.md)
