A rotary encoder reports movement as two changing contacts. Counting every edge on one contact produces a surprisingly bad knob: bounce can look like extra turns, and direction can become unreliable. Here we follow the order of both contacts and count complete electrical cycles.
Why two signals reveal direction
Quadrature means the two signal patterns are offset from each other. When you turn steadily, the pair moves through four states, changing one bit at a time. We encode A as the upper bit and B as the lower bit: 00, 01, 10 and 11 become 0, 1, 2 and 3. One valid sequence is 3 → 1 → 0 → 2 → 3. Its reverse means the opposite direction.
The contacts bounce, so one valid edge might briefly reverse and return. A transition table gives those opposite steps opposite signs. A jump changing both bits at once, such as 00 to 11, is impossible for one ideal edge. The code records that as invalid, clears its incomplete cycle and resynchronizes with the new observed state.
Parts to gather
- Original Raspberry Pi Pico with MicroPython 1.26
- Bourns PEC11R quadrature encoder; use its A, B and common C terminals
- Two 10 kΩ pull-up resistors, breadboard and short wires

Complete connections
| Connection | Purpose |
|---|---|
| Encoder common C → Pico GND, physical pin 38 | Verify terminal labels from the exact encoder drawing. |
| Encoder A → GP14, pin 19; A → 10 kΩ → 3V3 | External pull-up defines the open-contact level. |
| Encoder B → GP15, pin 20; B → 10 kΩ → 3V3 | Use 3V3(OUT), pin 36; leave push-switch terminals unused. |
Connect the named contacts
Use the terminal drawing for the exact encoder variant. Common C is a contact connection, not a positive supply. The two 10 kΩ resistors pull A and B toward 3.3 V when open. A closed contact draws approximately 0.33 mA. On modules with built-in resistors, verify where those resistors connect before substituting the module for the bare component.
GPIO means general-purpose input/output. This example reads GP14 and GP15; their physical header positions are 19 and 20. The encoder’s separate pushbutton, if fitted, is intentionally left unused so the experiment isolates rotation.
Complete MicroPython program
"""Pico: encoder A -> GP14, B -> GP15, C -> GND, external 10k pulls."""
TRANSITIONS = (0,-1,1,0, 1,0,0,-1, -1,0,0,1, 0,1,-1,0)
class Decoder:
def __init__(self, initial=3):
self.previous = initial
self.quarters = 0
self.position = 0
self.invalid = 0
def update(self, current):
if current == self.previous:
return 0
if current ^ self.previous == 3:
self.invalid += 1
self.quarters = 0
self.previous = current
return 0
self.quarters += TRANSITIONS[(self.previous << 2) | current]
self.previous = current
step = 0
if self.quarters >= 4:
step = 1
elif self.quarters <= -4:
step = -1
if step:
self.quarters = 0
self.position += step
return step
def main():
from machine import Pin
from time import sleep_ms, ticks_ms, ticks_diff
a, b = Pin(14, Pin.IN), Pin(15, Pin.IN)
decoder = Decoder((a.value() << 1) | b.value())
printed = ticks_ms()
while True:
decoder.update((a.value() << 1) | b.value())
now = ticks_ms()
if ticks_diff(now, printed) >= 250:
print("cycles=%d invalid=%d" % (decoder.position, decoder.invalid))
printed = now
sleep_ms(1)
if __name__ == "__main__":
main()
What a count means
The decoder accumulates signed quarter-steps. Four in one direction produce one whole count. Turning backward before completing a cycle subtracts from the accumulation. The resulting count is an electrical quadrature cycle, not a guaranteed one-click event: the relationship between mechanical detents and pulses depends on the chosen encoder variant.
The program polls approximately every millisecond and prints four times per second. Serial output and interpreter activity can still delay sampling. This is suitable for a slowly operated human knob; it is not a high-speed motor encoder interface. The invalid counter is evidence of observed bad transitions, while a zero counter does not prove that every edge was captured.
Test the state machine before the knob
The supplied host tests feed a full forward cycle, its reverse, a bouncing edge and a two-bit jump to the actual Decoder class. Those tests verify the algorithm independently of hardware. Then save the script as main.py on the Pico, open the console and turn the knob slowly. Note which direction increments the count; swapping A and B reverses the sign without changing the arithmetic.
- Turn five complete cycles one way, then back. The total should return close to its starting value when edges are captured.
- Wiggle gently near one contact transition. Opposite partial movements should cancel rather than generating endless counts.
- Turn much faster and watch the invalid counter. This exposes sampling limits instead of hiding them.
- Disconnect one signal with power off, then restart. The missing direction information should prevent useful counting; the decoder does not identify the unplugged wire for you.
When to improve the design
For faster motion, capture transitions with a hardware-supported method such as Pico’s programmable input/output subsystem, or use appropriate interrupt handling. Contact filtering must preserve the order of A and B; adding arbitrary large capacitors can distort that order. First record the problem you actually see, then select filtering and sampling together.
Challenge: why reset the partial count after a two-bit jump?
The missing intermediate state could have belonged to either direction. Keeping the partial count would turn uncertainty into a guessed movement. Resetting loses an incomplete cycle but avoids inventing its direction.
Sources and related learning
Explore the Tricky Circuit interactive lessons. This article presents a design and software checks; no physical build results are claimed.



