A general-purpose I/O pin connects one bit of a few registers to the outside world. On a typical 8-bit microcontroller each register has one bit per pin, and bit 0, the least significant bit, belongs to pin 0 of the port. A direction bit makes the pin an output or an input; which value means output differs between parts. On a part where 1 means output, with DIR_REG and OUT_REG pointers to the volatile direction and output registers as in Chapter 2, *DIR_REG |= 0x08u; makes pin 3 an output and *OUT_REG |= 0x08u; drives it high.
An input connected to nothing is floating: its voltage drifts and the bit can read either value. A pull-up resistor fixes this for a button. One end of the resistor goes to the supply, the other to the pin, and the button connects the pin to ground. Many parts have a pull-up inside, switched on by an enable bit. Released, almost no current flows, so the pin sits at the supply and reads 1; pressed, it is tied to 0 V and reads 0.
CURRENT THROUGH A PRESSED BUTTON
I=RpuVDD
Ohm's law across the resistor, while the button is closed and its own resistance is negligible. I is the current in A, VDD the supply in V, Rpu the pull-up resistance in Ω. A larger Rpu wastes less current while the button is held.
A mechanical contact does not close cleanly. It bounces, opening and closing for a few milliseconds, and a program that reads fast enough sees several presses. Software debouncing samples the pin every Ts and accepts a press only after k pressed samples in a row. One released sample resets the count.
DEBOUNCE CONFIRMATION TIME
tconfirm=kTs
Holds once the contact has settled closed: the next sample comes within Ts and k−1 more follow, so the press is accepted within tconfirm. The k samples span (k−1)Ts, so choose (k−1)Ts longer than the bounce time tb: no closed stretch inside the bounce is that long. k is a whole number; Ts, tb, tconfirm in s.
The function below must run every 5 ms, from the periodic timer tick built in the next section. The hardware can call a function each time that tick's flag rises: this call is an interrupt, and it pauses the main loop until the function returns. PIN_REG points to the volatile input register; the main loop reads pressed_count, so it is volatile too. With k=4, a press is accepted within 20 ms of the contact settling, and any closed stretch shorter than 15 ms is rejected.
#include <stdint.h>
#define BTN_MASK 0x01u
volatile uint8_t pressed_count = 0u; /* read by the main loop */
void sample_button(void) { /* timer interrupt, every 5 ms */
if ((*PIN_REG & BTN_MASK) == 0u) { /* 0 means pressed */
if (pressed_count < 4u) { pressed_count++; }
} else {
pressed_count = 0u; /* a released sample restarts */
}
}
The button counts as pressed while pressed_count equals 4.