Rotary encoders: count clicks and direction

A rotary encoder looks like a potentiometer, but it turns without an end stop and gives digital pulses instead of a voltage. You feel small clicks, the detents, as you turn it. Inside, two switches, A and B, open and close in a fixed order. The order tells the direction, and the number of changes tells the distance. This is an incremental encoder: it reports only movement. It does not report an absolute angle. Common parts are the bare EC11 encoder and the KY-040 module. Both also have a push switch in the shaft.

A pile of PCB-mount mechanical rotary encoders with metal frames, green bodies, black shafts and bent solder pins
Mechanical rotary encoders of the EC11 type, before soldering.
Photo: SparkFun Electronics, CC BY 2.0

Turn the encoder

Drag around the knob. Release it and it snaps to the nearest detent. The state diagram shows the pin state (A B) and the last transition that the state-table decoder saw.

How it works

Quadrature: A and B

A and B are two square waves with a 90° phase difference. Turn clockwise and A changes first (A leads). Turn counterclockwise and B changes first. The two channels never change at the same time. One full cycle has four changes, or transitions.

Gray code

Read A and B together as a 2-bit state. The states follow the order 11 → 01 → 00 → 10 → 11 in one direction and the opposite order in the other direction. Only one bit changes per step. This is a Gray code. A change of both bits at once is invalid: the decoder missed a state, or there was noise.

Counts per detent

Many EC11-type encoders give one full cycle per detent, so 4 transitions = 1 click. Others give half a cycle per detent (2 transitions), and the rest state changes between 11 and 00. The KY-040 modules use different encoders from different sellers. Turn one click and count the transitions to find out.

Pull-ups

The common pin (C) of the encoder goes to GND. A and B need pull-ups, so they read HIGH when their switch is open. Most KY-040 boards have 10 kΩ pull-ups from CLK and DT to the + pin, so connect + to 3V3. The SW pull-up position is often empty: use INPUT_PULLUP.

Bounce

The contacts of a mechanical encoder bounce, like a button. A bounce on A looks like A changes, then changes back. A state-table decoder counts that as +1 then −1, so the net count stays correct. A decoder that uses only the falling edge of A counts each bounce as a step. The step can be in the correct direction or in the wrong direction.

State-table decoding

Keep the previous state. When a pin changes, read the new state. Use a 16-entry table with the index (old << 2) | new. Each entry is +1, −1 or 0 (no change or invalid). Run it in an interrupt on both A and B, or poll fast enough that you never miss a state.

PCNT hardware counter

The ESP32 has a pulse counter (PCNT) peripheral that decodes quadrature in hardware. It has a glitch filter and uses no CPU time. The ESP32Encoder library uses it. This is the best choice for fast signals, for example motor encoders.

Motor encoders

Many gear motors have an optical or Hall-effect (magnetic) encoder on the motor shaft. These give clean quadrature signals without bounce, but at high rates (thousands of transitions per second). Use PCNT. Refer to DC motors. Check the supply voltage of the encoder: some need 5 V and give 5 V outputs.

Absolute encoders

An incremental encoder does not know its position after power-on. An absolute encoder does. The AS5600 is a magnetic sensor that reads the angle of a magnet on a shaft as a 12-bit value (0–4095) through I²C. Use it when you need the real angle.

Wiring

ESP32 GPIO 32 GPIO 33 GPIO 27 3V3 GND KY-040 CLK (A) DT (B) SW + GND 10 kΩ to + pull-ups on CLK, DT channel A channel B push switch, INPUT_PULLUP 3.3 V (do not use 5 V)
Connect + to 3V3, so that the on-board pull-ups give 3.3 V levels. For a bare EC11 encoder: connect the middle pin C to GND, A and B to the GPIOs with INPUT_PULLUP (or 10 kΩ external pull-ups), and the two switch pins to GND and GPIO 27.

Connections

KY-040 pinConnect toNotes
CLKGPIO 32Channel A.
DTGPIO 33Channel B. Swap CLK and DT to reverse the direction.
SWGPIO 27INPUT_PULLUP. LOW when pressed.
+3V3Supplies the pull-ups.
GNDGND

Any GPIO with interrupts can read an encoder. Do not use the strapping pins 0, 2, 5, 12 and 15. GPIO 34–39 operate only with external pull-ups. Optional hardware filter: 10 nF from A and from B to GND (with 10 kΩ pull-ups, about 0.1 ms).

Build steps

  1. Connect the moduleConnect the five wires as shown in the table.
  2. Install ESP32EncoderIn the Library Manager, search for “ESP32Encoder” by Kevin Harrington and install it.
  3. Upload sketch 1Open the Serial Monitor at 115200 baud. Turn the knob one click at a time.
  4. Set the counts per detentIf one click gives 2 instead of 1, set COUNTS_PER_DETENT to 2.
  5. Examine the directionIf clockwise gives negative numbers, swap the CLK and DT pin numbers in the code.

Code

1 · Hardware counter (ESP32Encoder)

attachFullQuad() counts all 4 transitions per cycle. attachHalfQuad() counts 2 and attachSingleEdge() counts 1.

encoder_pcnt.ino


              #include <ESP32Encoder.h>

              const int PIN_A = 32, PIN_B = 33, SW_PIN = 27;
              const int COUNTS_PER_DETENT = 4;   // full quadrature, 1 cycle per click

              ESP32Encoder encoder;
              long lastDetent = 0;

              void setup() {
                Serial.begin(115200);
                // Set this before attach. KY-040 has its own pull-ups: puType::none also works.
                ESP32Encoder::useInternalWeakPullResistors = puType::up;
                encoder.attachFullQuad(PIN_A, PIN_B);
                encoder.clearCount();
                pinMode(SW_PIN, INPUT_PULLUP);
              }

              void loop() {
                long detent = (long)(encoder.getCount() / COUNTS_PER_DETENT);
                if (detent != lastDetent) {
                  Serial.printf("Position: %ld (%s)\n", detent, detent > lastDetent ? "CW" : "CCW");
                  lastDetent = detent;
                }
                if (digitalRead(SW_PIN) == LOW) {   // push the knob to set zero
                  encoder.clearCount();
                  lastDetent = 0;
                  Serial.println("Zero");
                  delay(300);                       // simple debounce for the switch
                }
                delay(5);
              }
            

2 · State table with interrupts on A and B

No library. The same method as the simulator with “each edge”.

encoder_table.ino


              const int PIN_A = 32, PIN_B = 33;
              const int TRANSITIONS_PER_DETENT = 4;

              // index = (old state << 2) | new state, state = (A << 1) | B
              const int8_t QEM[16] = { 0, -1,  1,  0,
                                       1,  0,  0, -1,
                                      -1,  0,  0,  1,
                                       0,  1, -1,  0 };

              volatile int32_t transitions = 0;
              volatile uint8_t prevState = 0;

              void IRAM_ATTR onChange() {
                uint8_t s = (digitalRead(PIN_A) << 1) | digitalRead(PIN_B);
                transitions += QEM[(prevState << 2) | s];   // bounce: +1 then -1
                prevState = s;
              }

              void setup() {
                Serial.begin(115200);
                pinMode(PIN_A, INPUT_PULLUP);
                pinMode(PIN_B, INPUT_PULLUP);
                prevState = (digitalRead(PIN_A) << 1) | digitalRead(PIN_B);
                attachInterrupt(digitalPinToInterrupt(PIN_A), onChange, CHANGE);
                attachInterrupt(digitalPinToInterrupt(PIN_B), onChange, CHANGE);
              }

              void loop() {
                static long last = 0;
                long detent = transitions / TRANSITIONS_PER_DETENT;  // 32-bit read is atomic
                if (detent != last) {
                  last = detent;
                  Serial.printf("Position: %ld\n", detent);
                }
                delay(5);
              }
            

Do not use: the “falling edge of A” decoder

Many short tutorials use one interrupt on the falling edge of A and read B. It counts one step per cycle. A bounce at the falling edge of A gives an extra count in the correct direction. A bounce at the rising edge of A also makes a falling edge. At that time B has the other level, so the decoder counts a step in the wrong direction. The position drifts. Use sketch 1 or sketch 2 instead.

naive_decoder.ino (for comparison)


            void IRAM_ATTR onFallA() {
              position += digitalRead(PIN_B) ? 1 : -1;   // each bounce on A counts again
            }
            // attachInterrupt(digitalPinToInterrupt(PIN_A), onFallA, FALLING);
          

Troubleshooting

One click gives 2 or 4 counts

This is normal. Divide by the transitions per detent of your encoder (4 or 2) and of the decode mode. Turn exactly one click and print the raw count.

The count jumps or goes backward

Use a state-table decoder or PCNT. Do not use the naive decoder. Add 10 nF capacitors from A and B to GND. Make sure that the pull-ups are present and that + is on 3V3.

Nothing changes

Make sure that the common pin (bare encoder) is on GND. On the KY-040, + must have power, or CLK and DT have no pull-ups. Make sure that the pin numbers in the code agree with the wiring.

Resources