How does encoder mode work on STM32 timers?
Encoder mode configures a timer to decode quadrature encoder signals using two input channels (TI1 and TI2, typically mapped to CH1 and CH2 pins). A quadrature encoder produces two square waves 90 degrees out of phase — when the shaft rotates forward, channel A leads channel B by 90 degrees; when it rotates backward, B leads A. The timer hardware decodes this phase relationship automatically: the counter increments for forward rotation and decrements for reverse rotation, all with zero CPU overhead.
Three encoder modes are available: Mode 1 counts on TI1 edges only (2x resolution), Mode 2 counts on TI2 edges only (2x resolution), and Mode 3 counts on both edges of both channels — giving 4x resolution (four counts per encoder slot). For a 1000-line encoder in Mode 3, you get 4000 counts per revolution, corresponding to 0.09-degree angular resolution. The timer hardware also includes digital noise filters (ICxF bits) that reject glitches shorter than a configurable number of clock cycles — essential in electrically noisy motor environments.
The counter naturally handles direction changes without software logic. Firmware simply reads TIMx->CNT to get the current position. For absolute position tracking beyond the 16-bit counter range (0-65535), enable the update interrupt and maintain a software overflow/underflow counter, extending the range to 32 bits. The counter direction bit (DIR in the CR1 register) indicates the current rotation direction. ARR is typically set to the maximum (0xFFFF for 16-bit timers or 0xFFFFFFFF for 32-bit timers) to maximize the range before overflow.
Source: Timers & PWM Q&A
