The simplest software debounce is to wait, after detecting a press, for longer than the switch’s maximum bounce duration, and then read the pin again to confirm that it is still pressed.
if (!(GPIOC->IDR & BTN_PIN)) { // button pressed (active-low)
delay_ms(20); // wait for bounce to settle (>10 ms typical)
if (!(GPIOC->IDR & BTN_PIN)) { // confirm still pressed
GPIOA->ODR ^= LED_PIN; // take action
while (!(GPIOC->IDR & BTN_PIN)); // wait for release
delay_ms(20); // debounce the release too
}
}
This works but blocks the CPU for 20 ms twice per button press. The same waiting can be done without blocking, by a state machine that starts a timer on the first edge and ignores the pin until it expires, or one that requires the pin to hold the same value for several consecutive samples. That is a different machine from the two-state toggle in Section 2.6, which turns a level into an edge and does not debounce.
Hardware debouncing, with an RC filter or a digital timer, does not tie up processor cycles. What it costs is another small component on the board and the wiring for it, and it is hard to revise for a different switch, so it has to be designed with some tolerance. Software debouncing is flexible: if the switch is changed, you edit the code and reflash. It is also simple, and it needs no extra components. What it costs is processor cycles, spent waiting for the bouncing to stop. In practice a small capacitor together with a short software delay covers both sides. In Lab 2’s Technical Study you learn how to select an appropriately sized capacitor for a given switch.