MyRoboPath
microcontrollers12 min readUpdated 2026-03-01Intermediate

Precise Quadrature Optical & Magnetic Encoder Decoding in C++

Implement glitch-filtered 4x quadrature encoder decoding using external GPIO hardware interrupts and lookup state transition tables.

Kenji Takahashi
Kenji Takahashi
Principal Embedded Systems Engineer

Key Engineering Takeaways

  • A 16-element transition table in Flash RAM enables direction and count updates in fewer than 10 assembly instructions.
  • Declare tick count variables as `volatile int64_t` and protect reads on 8-bit/32-bit MCU boundaries using atomic blocks.
  • Calculate speed via low-pass filtered numerical differentiation $\omega = \frac{\Delta \theta}{\Delta t}$.
Prerequisites
  • Hardware interrupts
  • Bitwise shifting

Lookup Table Fast ISR Implementation

By storing the previous 2-bit state and shifting in the new 2-bit state, a 4-bit index `(prev_state << 2) | new_state` instantly returns +1, -1, or 0 (invalid glitch).
Tags:#Encoders#Interrupts#ISR#State Machine#C++#Motion Control