Inputs and Polling
In earlier chapters, we’ve explored GPIO pins primarily as outputs—driving LEDs on and off. However, GPIO pins can also be configured as inputs, allowing your program to read signals from the physical world, like button presses or switch toggles. In this chapter, we'll learn how to read these input signals and do something useful with them.
Reading Button State
The micro:bit v2 has two physical buttons, Button A and Button B, connected to GPIO pins configured as inputs. Specifically, Button A is connected to pin P0.14, and Button B to pin P0.23. (You can verify this from the official pinmap table.)
Reading the state of a GPIO input involves checking whether the voltage level at the pin is high (3.3V, logic level 1) or low (0V, logic level 0). Each button on the micro:bit is connected to a pin. When the button is not pressed, that pin is held high; when the button is pressed, the pin is held low.
Let's now apply this knowledge to reading the state of Button A by checking if the button is "low" (pressed).
#![no_main] #![no_std] use cortex_m_rt::entry; use embedded_hal::digital::InputPin; use microbit::Board; use panic_rtt_target as _; use rtt_target::{rprintln, rtt_init_print}; #[entry] fn main() -> ! { rtt_init_print!(); let board = Board::take().unwrap(); let mut button_a = board.buttons.button_a; let mut button_state = false; loop { if button_a.is_low().unwrap() { if button_state == false { button_state = true; rprintln!("Button A pressed"); } } else { if button_state == true { button_state = false; rprintln!("Button A not pressed"); } } } }
We spin looking at the button state, and report anytime that state changes.