What is Freeside?

Freeside is a Georgia nonprofit corporation, organized to develop a community of coders, makers, artists, and researchers in order to promote collaboration and community outreach. Learn more »

Arduino Rotary Encoder Library with Velocity Sense

While working on the constant current load project I found that while nice, the multiple turns required to turn up the power up was a little annoying when you just wanted to hurry up and get to a high value. The standard solution is to have a "fine" and "course" knob. Since I designed the input in the digital realm it seemed like software was the obvious solution. Why not sense the speed the user is turning the knob and extrapolate the pace of change based on that input. It seems intuitive to me. I implemented it as a little C++ library that you can drop into your arduino/libraries directory.

Here is the most trivial implementation of the library.
#include <RotaryEncoder.h>;
RotaryEncoder encoder(A0,A1,5,6,1000);
void setup()
void loop()
  int enc = encoder.readEncoder();
  if(enc != 0) {

Inside the library, the code counts the number of the sequential clicks in one direction within less than the time constant you pass in when you instantiate the object. In the above example, the selected time constant is 1000┬Ás (the 5th variable). If the user waits longer than that amount of time the counter resets. If the user changes direction the counter resets. To determine the return value I divide the counter by the 4th variable you pass in, 6 in this case, and then multiply that by 5 (the 3rd  variable) and return that value. Turning anti-clockwise is the same except that I make it negative (multiply value by -1). So, if you turn the knob 30 times in a clockwise direction I will return (30/6)*5 or 25. Bear in mind that 30 times doesn't mean 30 detents of the encoder. Each encoder is different. The ones I have in my drawer return 4 times per detent, YMMV.

The library is available here.

In order for this to work, you need to have clean reads of the encoder (or it will reset the counter). To do this effectively, you really need to "debouce" the switch. I've never been able to effectively do this in software. I use 10000pF capacitors between the A pin and GND and B pin GND. This makes the circuit very well protected from bad reads. Furthermore, you need to check the value more frequently than it can change otherwise the quadrature signal will become out of sync and you will not know what direction you are turning.


Post a Comment