ohmio

Circuits / Sensors

Arduino UNO: KY-040 rotary encoder counter

A rotary encoder gives two square waves a quarter of a cycle apart: at each fall of CLK, DT high means clockwise and DT low counter-clockwise. The sketch ignores a CLK change under 8 ms after the last one, so contact bounce of up to 5 ms does not miscount.

Arduino UNO: KY-040 rotary encoder counter, simulated on a breadboard

Tap a part to see its voltages and currents. It is a model, not a measurement.

What do you need?

The AliExpress links are affiliate links: if you buy through them ohmio.dev gets a commission, at no extra cost to you. Affiliate links

This page is a guide: the numbers come from a simulation, and real parts vary. Check your parts before you power the circuit. Safety and responsibility

How does an Arduino count the clicks of a rotary encoder?

A KY-040 encoder has 20 clicks a turn, 18° each, and two contacts, CLK and DT, that close a quarter of a cycle apart. When CLK falls, DT tells the direction: HIGH is clockwise and LOW counter-clockwise. The sketch counts up or down at each fall and prints the count. In the model, turning the shaft from 0° to 90° prints 1, 2, 3, 4, 5, and turning back to 36° prints 4, 3, 2. Pressing the push switch SW sets the count to zero. Real contacts chatter when they change, 2 ms in this model, so the program ignores a CLK change less than 8 ms after the last one it accepts. On a real module, if clockwise counts down, swap the CLK and DT wires. At a hand's speed the count is exact; a very fast turn can add one click.

Values from the Protoboard ISO simulation: a model, not a bench measurement.