A quadrature encoder has two output channels, A and B, that switch in a pattern a quarter of a cycle apart. Because the order in which they change reverses when the shaft reverses, your code can tell direction from the sequence and count steps up or down.
Key takeaways
- Channels A and B are square waves offset by 90 degrees, so only one of them changes at a time.
- The order of the A and B states (00, 01, 11, 10 in one direction, the reverse in the other) gives direction.
- Counting every edge of both channels gives four counts per cycle (x4 decoding).
- Swapping the A and B wires, or the sign in your code, reverses which direction counts as positive.
Two Channels, Ninety Degrees Apart
A quadrature encoder is a position sensor that gives two digital signals, called A and B, as the shaft turns. Each signal is a square wave. One full cycle of A is one pulse, and B is the same wave shifted by a quarter of a cycle, which is 90 degrees, hence the name quadrature, meaning a quarter.
With a single channel you can count pulses but not tell whether the shaft is going forward or backward, because the pulses look the same either way. The second channel adds the missing information. On a robot this matters, because wheels turn both ways and a count that only goes up will quickly drift from the truth. The wider picture of using encoders on wheels is in the robot wheel encoder guide.
Reading the Phase Sequence
The phase sequence is the order in which the two channels change. In one rotation direction, A rises first and B follows a quarter-cycle later. In the other direction, B rises first and A follows. Direction is therefore decided by which channel was ahead.
Written as the pair of states AB, one direction goes 00, 01, 11, 10, then back to 00. The opposite direction runs the same list backwards: 00, 10, 11, 01, 00. Only one bit changes at each step. That is a Gray code, and it is the reason the sequence is robust: two bits never change at the exact same instant in a healthy encoder, so a reading never lands on a random in-between value.
Which direction is called forward is a convention. It depends on how the encoder is mounted and which wire goes to which pin. If your robot counts down when it moves forward, swap the A and B wires or flip the sign in code. Do not change the decoding logic.
State Table
A decoder compares the previous state with the new state and decides what happened. The table below uses the convention that 00, 01, 11, 10 is the positive direction.
| Previous AB | New AB | Meaning | Count change |
|---|---|---|---|
| 00 | 01 | forward step | +1 |
| 01 | 11 | forward step | +1 |
| 11 | 10 | forward step | +1 |
| 10 | 00 | forward step | +1 |
| 00 | 10 | reverse step | -1 |
| 10 | 11 | reverse step | -1 |
| 11 | 01 | reverse step | -1 |
| 01 | 00 | reverse step | -1 |
| 00 to 11, or 01 to 10 (either way) | – | invalid, a state was skipped | 0 (flag an error) |
An invalid transition means the code missed a step, which is useful information: if you count them, you know how often it happens. In code the table becomes a 16-entry lookup indexed by the previous and new states.
// Untested example for illustration. A on pin 2, B on pin 3 (Uno interrupt pins).
// Index = (previous AB << 2) | new AB. A is the high bit.
const int8_t STEP[16] = { 0, +1, -1, 0,
-1, 0, 0, +1,
+1, 0, 0, -1,
0, -1, +1, 0 };
volatile long count = 0;
volatile uint8_t prevAB = 0;
void onChange() {
uint8_t ab = (digitalRead(2) << 1) | digitalRead(3);
count += STEP[(prevAB << 2) | ab];
prevAB = ab;
}
void setup() {
pinMode(2, INPUT_PULLUP); pinMode(3, INPUT_PULLUP);
prevAB = (digitalRead(2) << 1) | digitalRead(3);
attachInterrupt(digitalPinToInterrupt(2), onChange, CHANGE);
attachInterrupt(digitalPinToInterrupt(3), onChange, CHANGE);
}Read count in the main loop with interrupts briefly disabled, because it is a multi-byte variable. The Arduino reference for attachInterrupt() lists which pins support interrupts on each board. The interrupt side is covered step by step in reading a rotary encoder with Arduino interrupts.
Counting on Both Edges
Counting on both edges means treating every change of either channel as a count. One full cycle contains four state changes, so you get four counts per cycle. This is called x4 decoding. Counting only the rising edge of A gives x1, and counting both edges of A gives x2.
Higher decoding gives finer position and smoother speed readings, but it also means four times as many interrupts per second. The arithmetic for turning counts into wheel distance is in the encoder counts and distance calculator, and you can use the same encoder in the speed loop of PID motor speed control with an encoder.
Missed Counts at High Speed
Missed counts happen when edges arrive faster than your code can read them. If two edges arrive before the interrupt handler runs, the handler sees a state two steps away from the previous one, and the table gives zero or the wrong sign. The count then drifts, and the error does not correct itself.
Ways to reduce it: keep the interrupt handler short, avoid Serial.print() and long calculations inside it, use digitalRead() sparingly or read the port register directly, and do not run other long interrupts. A slower motor, or a lower decoding level such as x2, also reduces the load. Count rate is the encoder’s counts per revolution multiplied by revolutions per second, so a high-resolution encoder on a fast shaft is the hardest case. Also keep the main loop free of blocking delays, as in a non-blocking millis state machine, so that the code can read the count regularly.
Wiring and Pull-Ups
Many encoder outputs are open-collector or open-drain, which means they can pull the line low but need a pull-up resistor to make it high. The Arduino’s INPUT_PULLUP mode provides one internally. Some modules include their own pull-ups, and some magnetic encoders on gearmotors are push-pull and need none. Check the datasheet or the listing for your encoder to see which type you have.
Supply the encoder from the voltage its datasheet states, usually 3.3 V or 5 V, and make sure its output levels suit your microcontroller. Keep encoder wires away from motor wires, because motor switching noise can add false edges. Use a common ground, and add a small capacitor close to the encoder supply if you see random extra counts. The behaviour of a full build with an encoder is shown in the straight-line encoder robot.
How to check this yourself
- Print
countto the Serial Monitor and turn the shaft slowly by hand in one direction; the count should rise steadily. - Turn it the other way; the count should fall. If it is reversed, swap the A and B wires.
- Turn the shaft exactly one revolution and compare the count with the expected counts per revolution.
- Spin it fast by hand, return it to your marked start position and check whether the count returns to the same value.
Common mistakes
- Counting only channel A and wondering why direction is unknown.
- Putting
Serial.print()inside the interrupt handler. - Forgetting pull-ups on open-collector outputs, which gives random counts.
- Reading a 16-bit or 32-bit count without disabling interrupts.
Quick checklist
- Connect A and B to interrupt-capable pins if you want x4.
- Use the state table or a 16-entry lookup.
- Enable pull-ups if the outputs are open-collector.
- Keep the interrupt handler very short.
- Verify direction and count by hand before driving the motor.
Frequently asked questions
How does a quadrature encoder detect direction?
It has two channels, A and B, offset by a quarter of a cycle. In one direction A changes before B, and in the other direction B changes before A. By comparing the previous and current states of both channels, the code decides whether to add or subtract one count.
What does x4 decoding mean?
x4 decoding counts every edge of both channels. A full cycle has four edges, so each cycle gives four counts. Compared with counting one edge of one channel, you get four times the position resolution, at the cost of four times as many interrupts per second.
Why does my encoder count drift?
Common causes are missed edges at high speed, electrical noise on the signal wires, missing pull-ups, and a slow or blocked interrupt handler. Keep the handler short, separate encoder wires from motor wires, check pull-ups, and count invalid transitions to see how often steps are skipped.
Related reading
- Learn hub: more encoder and Arduino explainers.
- How an H-Bridge Works: Four Switches, Two Directions
About the author and how this is kept accurate
Written, checked and maintained by Jignesh Panchal of Jaadu Digital. Figures in worked examples come from the stated assumptions, not from a bench test of our own. Read the editorial standard, follow the author on LinkedIn, or send a correction. Last reviewed: November 2026.



