[Pete] needed a rotary encoder for one of his project so he set out to build his own. As the name implies, a rotary encoder measures rotation by encoding “steps” into electrical signals which can be measured by a microcontroller (or used in numerous other ways). Knowing the degrees of movement for each step will allow you to calculate precise distance traveled in applications like robot wheels. Or you can simply use the rotating shaft as an input device which navigates menus or settings.
This concept is a good one to understand. We had originally planned to build rotary encoders for the multi-person Duck Hunt at Hackaday’s 10th Anniversary but the build-off crew had difficulty getting the system to work. In [Pete’s] case he’s using photointerrupters (apparently the IR beam is easily detected through the white paper but usually these parts would be cut out of the disk). We were using reflectance sensors. Either way there’s a trick to detecting which direction a rotary encoder is turning. We’ll explain that for you after the break.
For ease of understanding we’ve straightened out the encoder wheel to this line of white and black boxes. Each one is a single step of the encoder. To measure direction you need two sensors; a single sensor would detect the same pattern of white and black boxes no matter which direction it was turned.
The two sensors are mounted “out of phase”. They are exactly 1/2 of a step apart. If you look at the image right now, sensor A detects a black box, sensor B would register a white box. Because they are 1/2 step apart, they will never change state at the same time. It will always be one after the other no matter which way the pattern moves.
As long as the current state is known, the next sensor to change will denote the direction the encoder pattern is moving. If you move the pattern itself to the right (the sensors are stationary) the next thing to happen will be sensor B going from white to black. But if you move the pattern to the left, the next thing to happen will be sensor A going from black to white. The pattern of outputs is known as Gray Code and can be parsed using a look-up table or with simple logic.
This concept is exceedingly simple if you take the time to boil it down to the core concept and work through what exactly is happening as we have here. That’s the case for most hardware concepts, and it’s well worth seeking out and digging into areas you don’t totally understand. It makes magical and mysterious sensors like magnetic rotary encoders easy to understand.