Skip to content

oudesnepelaar/Rotary-Arduino-library

Repository files navigation

This Arduino library allows easy interpretation of the Data/Clock pin values of a KY040 rotary encoder
and translates them into practically usable CW and CCW movement indicators.

CCW notch advances are represented by an int value of -1, CW turns by 1, no movement by 0.

A KY040 outputs Gray code, two out of phase block signals on the Clock and Data outputs.
The CLK/DT outputs advance their signals pretty fast while turning.
Advancing the knob to the next indentation (where the physical turning resistance increases
to hold the knob a bit tighter), could be called: a notch advance.
Then the KY040 CLK and DT block signals, flip state about 5x for each notch advance.

This can easily be monitored by hooking up the CLK/DT to LEDs and watching the blinking patterns
as the knob is rotated. Examining this pattern, one can conclude that the Gray code output by
the KY040 generally is stable and reliable, but interpreting it is a bit involved.

To translate the CLK/DT pulses into proper notch advances, a buffer is used to hold the changes
internally until 5 subsequent advances in the same direction have been registered.
This also takes away the problem of bouncing contacts, during the turning of the knob.

One needs to hook up the data outputs of the KY040 to 2 CHANGE interrupt inputs on the Arduino,
so the values can be processed with a guarantee that all state changes in the CLK / DT  values
are indeed captured.

This might under ideal circumstances also work with regular inputs (no interrupts), but the slightest
delay in the Arduino code main loop will likely cause some data changes to be missed. Missing any
values changes will turn into erretic behavior (misinterpretation of the turn direction, perceived
as jitter back and forth).

So, the way to succesfully interpret the KY040 output signals, relies on buffering the
pulses enough to slow down the rate of data, while also guaranteeing in some way that no
pulses are missed. This library will enable both.


Ferrie J Bank,
Amsterdam 21 February 2020

https://github.com/oudesnepelaar

About

An Arduino library for decoding KY040 rotary encoder data

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages