One of the first things anyone does when they start working with the Arduino is to connect it to a potentiometer and control the brightness of and LED or move a servo. Well, a rotary encoder may look like a potentiometer, but other than also having a knob, it is basically the complete opposite.
A rotary encoder is a device that you can rotate infinitely. Simple ones like this one I got from sparkfun have no real state like a pot does, so when you start up, you won’t be able to simply read from the encoder where it is turned to. But because you can keep turning it it has no beginning, middle or end anyways. However, if you keep track of that rotation in code, you can use it as a knob input you can turn up or down as much as you would like.
On most rotary encoders, when you rotate them, you will feel a bump. These are known as steps, and most rotary encoders like this guy have about 12 of these per rotation. But some have 200 or more. Basically this step is the minimum amount you can rotate the encoder to register any change.
Most simple encoders like this only make use of 3 pins, and one of those is ground. Those other two pins change state and are always either high or low, so they can only have a total of 4 combinations. 00, 01, 10, and 11. This is known as 2 bit gray code. So when you turn it, the arduino can say… Well you were at 01, and now you are at 00 so you move this way. Or you were at 01, but now you are at 10 so you must have moved the other way. You can see that this encoder has 5 pins, the other 2 are just a simple switch that is engaged when you press down. (see the second illustration on the right)
It sounds super simple, and it kinda is, but what we can do is every time a value changes we can check what direction it moved. Then if we increment a value every time it turned one way, and deincrement it when we move one step the other, we can keep track of how much it has moved since we started. So if you want a knob that can turn up to 11, this is your guy. (there is a double pun in there I promise)
Read more: Rotary Encoder + Arduino