Buttons¶
Buttons are useful to control different states your program, having two of them allows to make all sorts of interaction possible.
Think about how many functions you could do with just two buttons on old electronic watches, such as setting time and date, starting timers, changing alarms etc.
Check for a button press (built-in buttons)¶
The basic thing you need to learn is reading button presses.
If you are using the micro:bit built-in buttons this is just a one-liner:
from microbit import *
while True:
if button_a.is_pressed():
display.scroll("A")
The function is_pressed() called on the button_a
variable returns True if the button was pressed.
What if we want to display A only if the button is not pressed? Easy, just add a not
in front of the line.
not button_a.is_pressed()
A very similar code works for javascript:
if (input.buttonIsPressed(Button.A) {
display.scroll("A")
})
Only difference is that for Javascript we can’t use the ‘not’, but we use the exclamation mark “!” instead.
Check for a button press (external-button)¶
If you need to use an external button, let’s say connected at P0 and GND, we can use the read_digital()
function
pin0.set_pull(pin0.PULL_UP)
while True:
if (pin0.read_digital() == 0):
display.scroll('PRESSED')
The first line enables a Pull-up resistor, an internal component that keeps the pin value to 1 unless we press the button.
This is needed since we want to read 0 only when the button is pressed, and any interference could be misleading.
Example: Direction arrows¶
Requirements:
-
If the A button is pressed the Left Arrow is displayed.
-
If the B button is pressed the Right Arrow is displayed.
Blocks editor version¶
Javascript version¶
basic.forever(() => {
if (input.buttonIsPressed(Button.A)) {
basic.showArrow(ArrowNames.West)
} else {
if (input.buttonIsPressed(Button.B)) {
basic.showArrow(ArrowNames.East)
} else {
basic.clearScreen()
}
}
})
Python version¶
import * from micropython
while True:
if button_a.is_pressed():
display.show(Image.ARROW_W)
elif button_b.is_pressed():
display.show(Image.ARROW_E)
else:
display.clear()