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:
7Backward
track("02310");Expected output:
-4Learn it first
- Timers and PWM · Prescalers, auto-reload, input capture, output compare and dead time.
More Timers and PWM problems
- Servo pulse width · Turn an angle into the compare value for a hobby servo's pulse.
- Prescaler and auto-reload · Choose PSC and ARR for a 16-bit timer to hit an update frequency.
- Frequency from input capture · Compute a signal's frequency from two capture timestamps on a 16-bit timer.
- Duty cycle from captures · Measure a PWM signal's duty cycle in tenths of a percent.
- Software PWM · Drive four PWM channels from a timer tick on pins without PWM hardware.
- Fan speed from tach pulses · Compute a fan's RPM from captured tach pulse times, and report 0 when it stalls.
- Fix: long delays end far too early · Delays over about four seconds come out wrong.
- Driver: a millisecond delay on a hardware timer · Program a timer's prescaler and auto-reload, and wait for exactly one period.
- Fix: 100 % brightness still flickers · A duty-cycle conversion uses the auto-reload value instead of the period length.
- Greenhouse: fan speed from temperature · Map a temperature to a PWM duty cycle, without stalling the fan at low speed.
- Robot gripper: servo angle to timer value · Turn a servo angle into the timer's compare value, within the gripper's mechanical limits.