Introduction to Rotary Encoders
April 14, 2011 Leave a comment
The other day, I was at Ax-Man, the local surplus store. I ran across a bin of rotary encoders and thought, “I need to play around with some of these.” I picked up two of them at about a dollar a piece and brought them home.
Rotary encoders look a bit like rotary pots, except they don’t have starting and stopping points. Instead, a rotary encoder will continue to turn indefinately. Also, instead of producing a varying resistance like a pot does, the encoder produces gray code. The units I got produce 4-bit gray code, meaning that it has five pins: 1 common pin and four signals producing binary patterns. Each time the knob is turned one click in either direction, the pattern of binary changes. By comparing the before and after pattern, a circuit can determine if the user turned the knob to the left or right and by how many clicks.
With the house to myself last night, I opened up my box of electronics testing tools and got to work. I developed the circuit below:
With this circuit, I have an arduino powering the common pin on the encoder via the 5V line. Two signal pins are used similarly to the way buttons are used with a microcontroller (the signals are either on or off; there is no analog value). Pull down resistors are used on the signal lines. This allows the Arduino to read either high or low values on digital pins 2 and 3. This produces one of four possible combinations: 00, 01, 10, 11.
To note: rotary encoders come in several bit resolutions. As I said, mine are 4 bit, which are probably overkill. I’m only using the first two signal pins, which basically causes my encoder to act like a 2-bit encoder by dropping the last two bits.
By comparing the current bit pattern to the previous, the arduino determines if a clockwise or counterclockwise click has been made. In my example code, a clockwise turn increases a pwm voltage on pin 9, which is read by my multimeter. Similarly, the counter clockwise turn decreases the voltage. The program also displays the octal value of the voltage supplied by pin 9 via the serial output.
Download the code here.
Video overview: (http://www.youtube.com/watch?v=afi-4UNPBlY)