WIRING of KY-040 Rotary Encoder plus Demo Code

Hi All,
I have played quite a bit with this rotary encoder
and got to several conclusions:

  1. You must use ISR to detect A and B pin changes
    or you will miss ticks:

// attach interupt handler to both pins 2 and 3:
attachInterrupt(0, rotEncIntHand, CHANGE);
attachInterrupt(1, rotEncIntHand, CHANGE);

  1. You must recognize 3 stages which
    constitute a tick from one position to its neighbour:
    a. aVal == bVal - prev position, let prevVal = aVal
    b. aVal != bVal - this is where the direction of the transition
    is recognized: if aVal != prevVal - clockwise
    if bVal != prevVal - counter clockwise
    c. (aVal == bVal) && (aVal != prevVal)
  • only when you see this state you can be sure the tick really happened.
  1. Capacitors between each pin and the ground are usefull.
    I use 0.1muF. But you still have to wait
    delayMicroseconds(msWaitBeforePinCheck)
    before reading the pins (see in the code below).
    I found the msWaitBeforePinCheck value by trial and error,
    but the range seems to be pretty wide - from 10microSec to 0.5ms.

My code:

testRotEncoder.ino (3.56 KB)