Reading a Rotary Encoder with Arduino

Reading a Rotary Encoder with Arduino — photograph from the project archive.

A rotary encoder provides relative movement as two phase-shifted digital signals. This small sketch turns changes on those signals into a signed counter and prints the count, making it a useful first step before connecting an encoder to a motor-control application.

How the project works

The loop reads channel A and compares it with the previous state. When A changes, channel B determines whether the count increases or decreases. The program prints the updated position count at 9600 baud.

An 800 microsecond delay is used as a simple debounce measure. This is polling code, so its performance depends on how frequently the loop runs; adding other blocking work can cause transitions to be missed.

Hardware and configuration

ItemIn the supplied code
Channel A / CLKD3
Channel B / DTD4
Input modeINPUT
Debounce delay800 microseconds

Working with the supplied code

Confirm that the encoder outputs have a defined idle level through the module or external pull-ups. The saved sketch does not enable the Arduino’s internal pull-ups.

The count represents detected transitions, not degrees and not an absolute shaft position. Rotate a known number of detents in each direction to establish the count per turn for the actual encoder. If movement appears reversed, review the A/B assignment and desired direction convention. This folder covers the encoder counter alone; the adjacent NEMA/EasyDriver projects add motor motion and different interrupt handling.

Reading a Rotary Encoder with Arduino — photograph from the project archive.
Reading a Rotary Encoder with Arduino — photograph from the project archive.

Source code and project files

Browse this project on GitHub. The files below are useful starting points for the sketches and references discussed in this post.

Download the used libraries (ZIP, 14.7 MB).

These notes describe the archived source and project media. The sketches have not been rebuilt or tested on hardware for this article.

Scroll to Top