The board has two press buttons labeled A and B. The following code reads the state of each button (False
if the button is not pressed and True
if the button is pressed).
threshold = 100
while True:
state_A = input.button_is_pressed(Button.A)
state_B = input.button_is_pressed(Button.B)
Edit the code above to get the following behavior. When pressing (and holding) button A, one of the LEDs turns on. When pressing (and holding) button B, another LED comes on. If no buttons are pressed, all LEDs are off.
Use the microbit to create an electronic die that can show values from 1 to 6. When you press button A, the microbit generates a random number from 1 to 6 (including both 1 and 6) using the code value = randint(1, 6)
. Next, it displays the result in the fashion of a physical die using LEDs. The code below shows how the different values can be displayed.
# show 1
basic.clear_screen()
led.plot(2, 2)
# show 2
basic.clear_screen()
led.plot(1, 1)
led.plot(3, 3)
# show 3
basic.clear_screen()
led.plot(1, 1)
led.plot(2, 2)
led.plot(3, 3)
# show 4
basic.clear_screen()
led.plot(1, 1)
led.plot(1, 3)
led.plot(3, 3)
led.plot(3, 1)
# show 5
basic.clear_screen()
led.plot(1, 1)
led.plot(1, 3)
led.plot(3, 3)
led.plot(3, 1)
led.plot(2, 2)
# show 6
basic.clear_screen()
led.plot(1, 1)
led.plot(1, 2)
led.plot(1, 3)
led.plot(3, 3)
led.plot(3, 1)
led.plot(3, 2)
If no buttons are pressed, all LEDs are off. If you hold button A, LEDs start coming on. For each additional second holding button A, another LED comes on. After holding button A for 10 seconds, all the LEDs are on for 1 second. Then they are switched off, and the cycle recommences.
If button A is released, all LEDs are switched off.
You can start with the following code.
import Math
nr_leds_on = 0 # keeps track of how many leds are turned on
while True:
# Convert n leds to row and column coordinates
rows = Math.floor(nr_leds_on / 5)
columns = nr_leds_on % 5
led.plot(columns, rows)
# increase the number of LEDs to be switch on by 1
nr_leds_on = nr_leds_on + 1
# if the number of LEDs to be swtiched on is larger than 25, we have to reset
if nr_leds_on > 25: nr_leds_on = 0
if nr_leds_on == 0: basic.clear_screen()
# Wait 500 ms
basic.pause(500)
Here is a breakdown of how the code works:
nr_leds_on
keeps track of the number of LEDs that are turned on.while True:
.Math.floor()
function and the modulo operator (%).led.plot(columns, rows)
.nr_leds_on
variable is incremented by 1.