Supplier photo of an assembled infinity mirror light cube illuminated on a dark background.
Supplier photo
Temu affiliate offer · Project idea

Build an infinity light cube

Listing specifies 5-volt direct current. Soldering required; battery and glue not included.

View kit on Temu

Tricky Circuit may earn a commission through these links. Product ideas have not been bench-tested by Tricky Circuit and are not verified lesson parts lists.

Read a Rotary Encoder Without Counting Every Bounce

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
Read a Rotary Encoder Without Counting Every Bounce. Encoder common C → Pico GND, physical pin 38 Encoder A → GP14, pin 19; A → 10 kΩ → 3V3 Encoder B → GP15, pin 20; B → 10 kΩ → 3V3
Original Tricky Circuit connection diagram. Nominal values are calculated; this build has not been physically tested.

Complete connections

ConnectionPurpose
Encoder common C → Pico GND, physical pin 38Verify terminal labels from the exact encoder drawing.
Encoder A → GP14, pin 19; A → 10 kΩ → 3V3External pull-up defines the open-contact level.
Encoder B → GP15, pin 20; B → 10 kΩ → 3V3Use 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.

  1. Turn five complete cycles one way, then back. The total should return close to its starting value when edges are captured.
  2. Wiggle gently near one contact transition. Opposite partial movements should cancel rather than generating endless counts.
  3. Turn much faster and watch the invalid counter. This exposes sampling limits instead of hiding them.
  4. 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.

📡Broadcast the signal — amplify the connection.

Leave a Reply

Temu affiliate offers

Find your next electronics project

Explore these do-it-yourself project kits. Check the selected option, included parts and instructions on each offer.

Tricky Circuit may earn a commission if you buy through these Temu affiliate links. These are product ideas; they have not been bench-tested by Tricky Circuit and are not verified lesson parts lists.

Supplier photo of a breadboard, jumper wires and assorted electronic components in a plastic storage case.

Supplier product photo

Try breadboard experiments

Breadboard, wires and assorted parts. Arduino controller board not included.

View kit on Temu

Supplier photo of an assembled blue surface-mount soldering practice board with a circular ring of small lights.

Supplier product photo

Solder a chasing-light board

Surface-mount soldering practice. Battery and battery holder not included.

View kit on Temu

Supplier photo of an assembled two-wheeled line-following car with a blue circuit board, two motors and an empty battery holder.

Supplier product photo

Build a line-following car

Soldering and assembly required. Check battery and track requirements before buying.

View kit on Temu