$USD
  • EUR€
  • £GBP
  • $USD
TUTORIALS MicroPythonmicro:bit

micro:bit MicroPython Tutorial 4: Getting the status of a LED

DFRobot Nov 09 2018 1056

In this tutorial we will learn how to read the status of a LED from the Micro:Bit‘s LED matrix, using MicroPython. If you need a guide on how to set the state of the LEDs, please check the previous post.

The code

As we did in the previous post, we will start by importing the display module, which gives us access to the functionalities related with the LEDs from the matrix.

from microbit import display

Now, we will set the brightness of one of the LEDs to an arbitrary value. I will be setting the top left LED (x and y equal to 0) to a brightness of 5, but you can use another LED or brightness value if you want.

Remember that we set the LED state by using the set_pixel method of the display module, passing as input the x and y coordinates of the LED in the matrix, followed by the brightness.

display.set_pixel(0,0,5)

Finally, to get the current value of a LED, we simply need to call the get_pixel method of the display module.

This method receives as input the x and y coordinates of the LED in the matrix (remember from the already mentioned previous post that both x an y are zero based, starting from the top left corner). As output, it returns the LED brightness, which can be a number between 0 (turned off) or 9 (full brightness).

print(display.get_pixel(0,0))

You can check below at figure 1 the expected output when running the previous commands on the MicroPython prompt.

Sending the MicroPython commands to turn On the LED and get its brightness

Figure 1 – Getting the LED brightness.

As an additional step, we will try to get the status of another LED from the matrix which we haven’t set.

print(display.get_pixel(4,4))

You can check at figure 2 the result obtained. As can be seen, it returns 0, which corresponds to the LED being Off. This makes sense since we did not change the state of the LED in position (4,4) and, by default, the LEDs are Off.

Sending the MicroPython command to get the status of a turned off LED

Figure 2 – Getting the status of a LED in Off state.

REVIEW