Simvik

Decode a quadrature encoder

Turn A/B channel transitions into +1, -1 or 0 steps with a lookup table. A medium embedded C problem (Timers and PWM), run and graded in the browser.

medium · Timers and PWM · encoder · lookup-table · gray-code

A rotary encoder has two outputs, A and B, a quarter cycle apart. Sampled as a 2-bit state (A is bit 1, B is bit 0), turning forward goes through 00 → 01 → 11 → 10 → 00, and backward through the same states in reverse.

quad_step(prev, now) returns +1 for a forward step, -1 for a backward step, and 0 when nothing changed or when both bits changed at once (an invalid jump: a step was missed, so it is better not to guess).

Starter code

int8_t quad_step(uint8_t prev, uint8_t now) {
  if (now > prev) return 1;
  if (now < prev) return -1;
  return 0;
}

Example tests

Forward, nearly two full cycles

track("01320132");

Expected output:

7

Backward

track("02310");

Expected output:

-4

Learn it first

  • Timers and PWM · Prescalers, auto-reload, input capture, output compare and dead time.

More Timers and PWM problems