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 to open the editor in a separate browser tab.

To install the program, copy the hex file onto your micro:bit. See this guide for getting started with Javascript Blocks.

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

 

MicroPython

To run the MicroPython version of the code, open up the online Python editor here and paste the following code into the editor window.

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.

 

Arduino

Make sure that you have your Arduino environment set up for micro:bit by following this guide.

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

// 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.

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

This page (Blinking an LED) was last updated on Mar 08, 2024.

Text editor powered by tinymce.