Sphere
Log in Join
☆ 11

encoder reading misses steps at high speed on arduino

Arduino Nano, rotary encoder on pins 2/3 using interrupts. At slow rotation I get correct counts, but when I spin the encoder fast, counts are missed - a full turn that should give 20 detents gives maybe 12. I'm using attachInterrupt with CHANGE on both pins and a simple state machine in the ISR to determine direction. ISR just increments/decrements a volatile long. Is the ISR too slow, or am I missing transitions because both pins change at once? Could noise be causing extra interrupts that I'm misreading? Do I need to disable interrupts while reading the count in loop()?

⚑ Report

4 replies

☆ 0
G glitch ·2026-11-11#1

On a Nano, pins 2 and 3 are the only external interrupts, good. Missing steps at speed usually means the ISR isn't capturing both edges fast enough, or you're reading a multi-byte volatile (a long is 4 bytes on AVR) without atomic protection - an interrupt can fire between bytes and you read a torn value. Disable interrupts briefly when reading: noInterrupts(); long copy = count; interrupts(); That alone can fix 'missing' counts that are actually corrupted reads. Also check your state machine handles the full quadrature sequence.

⚑ Report
☆ 0
C cache ·2026-11-12#2

I wasn't disabling interrupts when reading - I'll add that. My state machine is the common one that looks at both pin states and compares to previous. At high speed, both pins can change between interrupts, so I might skip a state. Is there a better approach?

⚑ Report
☆ 0
F ferret ·2026-11-13#3

Use a proper quadrature decoder that reads the full 2-bit state on every interrupt and uses a lookup table: oldState<<2 | newState gives a 4-bit index, and a table maps it to +1/-1/0. This handles skipped states gracefully. Also keep the ISR minimal - read the port registers (PINB/PIND) directly instead of digitalRead. Some people use an interrupt on one pin and a regular input on the other, halving interrupt load.

⚑ Report
☆ 0
P plastic2 ·2026-11-15#4

Two fixes did it: atomic read with interrupts disabled in loop, and a lookup-table decoder reading the port register directly in the ISR. Now fast spins give the right count. The torn 4-byte read was silently corrupting values - I'd have never guessed. If counts look wrong at speed on AVR, protect multi-byte volatile reads first, then optimize the ISR.

⚑ Report
Log in to reply.