TUTORIALS micro:bit

## micro:bit JavaScript Blocks Editor: Turning LEDs on and off

DFRobot Nov 23 2017 243

### The functions to use

#### So, if for example we want to light the first LED we pass the coordinates (0,0) and for the last LED we pass (4,4).

```led.plot(0, 0);
led.plot(4,4);```

#### So, to turn off the previously lighted LEDs, we can simply use the following commands and confirm the result on the simulation environment.

```led.unplot(0, 0);
led.unplot(4,4);```

#### Figure 2 – Turn off LEDs on the micro:bit simulation.Finally, if we just want to toggle the current state of the LED, we can use the toggle function of the same namespace, passing as input the x and y coordinates of the LED, again using the same coordinates system.

`led.toggle(2, 2);`

### The code

#### In order to introduce a small delay between each iteration, we will use the waitMicros function of the control namespace, which blocks the execution for the number of microseconds specified as input. In this example I will delay 2000000 microseconds, which corresponds to 2 seconds, but you can play with other values.

```for (let x = 0; x < 5; x++) {
for (let y = 0; y < 5; y++) {
led.plot(x, y);
control.waitMicros(2000000);
led.unplot(x, y);
}
}```

#### Next we will achieve the same effect but using the toggle function. In this case, we call the toggle function at the beginning of the loop to turn on the LED and then call it again after the delay to turn off the same LED.

```for (let x = 0; x < 5; x++) {
for (let y = 0; y < 5; y++) {
led.toggle(x, y);
control.waitMicros(2000000);
led.toggle(x, y);
}
}```

#### The final complete code can be seen below.

```for (let x = 0; x < 5; x++) {
for (let y = 0; y < 5; y++) {
led.plot(x, y);
control.waitMicros(2000000);
led.unplot(x, y);
}
}

for (let x = 0; x < 5; x++) {
for (let y = 0; y < 5; y++) {
led.toggle(x, y);
control.waitMicros(2000000);
led.toggle(x, y);
}
}```