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.
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.
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).
You can check below at figure 1 the expected output when running the previous commands on the MicroPython prompt.
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.
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.
Figure 2 – Getting the status of a LED in Off state.