Skip to main content

Subsection 2.4.2 Part 2: The Toggle Problem

The capacitor fixed the bounce, but there is a second problem that a capacitor cannot fix. Reading a pin on every iteration of the main loop, checking its state and acting on it, is called polling. It is the simplest way to respond to an input, and it is what we have been doing since button.c. A more general way to write it is to separate reading the pin from acting on what was read, which is what buttonPushed does below. Polling stops being enough as soon as the action we want is a toggle, and the next activity is where you work out why. Even with a debounced switch, consider this loop:
while (1) {
    buttonPushed = ((GPIOB->IDR & BUTTON_PIN) == 0);
    if (buttonPushed) {
        GPIOA->ODR ^= LED_PIN;   // toggle LED
    }
}

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.