Quick tip: Rotary Encoders - Understanding Your Knob
Rotary encoders are a reliable, switch-debounce-safe method of detecting (believe it or not) rotary motion. Rotary encoders (aka quadrature encoders) have a number of uses outside of making your keyboard look cool--they have historically been used as part of a closed-loop motor control system as the speed/direction input device.
It is useful to look at Gray code first to understand the exact way that rotary encoders work.
Gray code is a clever numerical encoding system that ensures only one bit changes at a time between adjacent values, minimizing errors during rapid transitions. This is particularly useful in rotary encoders, as it reduces misreadings caused by simultaneous bit changes.
What does this look like practically for human input devices? Two separate contacts that generate two square waves 90° out of phase. As the encoder is rotated, contact A and contact B are sequentially shorted to ground. Using internal pull-ups on a microcontroller, the following waveform is generated.
Each valid transition (Gray code count up!) can show you the direction of the step the rotary encoder has taken. How can you determine that direction and the validity of the transition in software? With a state machine!
Keep state and register a transition interrupt on pins A and B. Since the two independent contacts of the encoder cannot influence each other with switch bounce, we can get very precise and responsive input from a rotary encoder on every detent.
Note: this isn't the only way to handle quadrature encoders. If you don't want to use interrupts for whatever reason you can simply poll them quite quickly. Some detents may get lost but overall implementation could be simpler.
Here is QMK's encoder implementation:
https://github.com/qmk/qmk_firmware/blob/master/quantum/encoder.c
Have questions or comments? Be sure to check out our Discord!