Activity 2.4.3. The Toggle Problem.
(a)
Predict what this code will do if you press and hold the button for half a second. How many times will the LED toggle? Why?
(b)
The processor runs at 12 MHz, and one pass through the loop takes a few dozen clock cycles. Roughly how many times does it execute while a human holds the button down for 200 ms? How many toggles does that produce?
(c)
The fix is to act on the moment the button goes down, rather than on the fact that it is down. The code below uses a
buttonAlreadyPressed flag to do this. Trace through it: when does the LED toggle? When does it not toggle even though the button is down?
unsigned buttonAlreadyPressed = 0;
while (1) {
buttonPushed = ((GPIOB->IDR & BUTTON_PIN) == 0);
if (!buttonAlreadyPressed && buttonPushed) {
GPIOA->ODR ^= LED_PIN; // toggle on leading edge only
buttonAlreadyPressed = 1;
} else if (!buttonPushed) {
buttonAlreadyPressed = 0; // reset when released
}
}
(d)
On Thursday we’ll write this same logic a cleaner way, using the state machine design pattern. Read Section 2.6 before then, and we’ll discuss in class how its
state variable corresponds to the buttonAlreadyPressed flag above.
