EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 76
Rotary Encoders and Other Inputs
Reading knobs, keys and touch.
A rotary encoder outputs two pulse trains a quarter-cycle apart. Which one leads tells you the direction, and counting edges tells you how far it turned.
Read it with a pin-change interrupt or a fast timer, and debounce if the contacts are mechanical. Capacitive touch pads measure how a finger changes charge time.
Joysticks and sliders are simply potentiometers read by an ADC.
EXAMPLE
/* decode one step using a small state table, called on each pin change */
int8_t step(uint8_t a, uint8_t b) {
static uint8_t last = 0;
uint8_t now = (a << 1) | b;
int8_t d = 0;
if (last == 0 && now == 1) d = 1;
else if (last == 0 && now == 2) d = -1;
last = now;
return d;
}