Gray Code Decoder

One of the best ways of obtaining feedback from a rotating shaft is to use two optical encoders. If the encoders are out of sync with each other, they will produce a nice 2-bit Gray code[?] as the shaft rotates. This document describes how to deal with the resulting Gray code.

[Schematic of Gray Code Decoder] The schematic on the left uses four CMOS chips to convert the two bits of Gray code (labeled as 'Sin' and 'Cos') into a pulse bit and a direction bit. These two bits can then be fed into an up/down counter, or used in some other manner.

The Sin and Cos inputs are first passed through a buffer (4050); this greatly sharpens the rise and fall periods. An XOR gate (4070) creates a clock pulse which drives the D flip flops (4013) and the data selector (74157). The heart of the circuit is perfectly balanced, with otherwise unused gates acting as delays to keep signals from passing each other and producing 'hazards'. A jumper can be used to toggle the polarity of the direction bit, something that is very useful if one discovers that the completed project ends up running backwards. Debugging is made simpler by two status LEDs which display the final output.

[Photo of topside] [Photo of underside] Here are photographs of my first decoder. It is a satisfyingly dense package, with no free space on the board. The chips are socketed for easy repairs. The entire board can be swapped out since all I/O is routed through one connector. This makes it easy to reuse on project after project. I was so confident of the design that I skipped the breadboard prototype and went straight to perfboard. It worked.

Other strategies

There's more than one way deal with Gray code. Today the most common approach to is to feed both bits into a microcontroller and let software do the work of counting the Gray code. Chuck's Robotics Notebook has an excellent description of how to use a PIC microcontroller.

Honeywell have published this PDF which contains two approaches using digital logic. The first approach (Figure 2) is extremely simple but flawed; after the direction changes, it takes a few steps in the wrong direction before the direction bit flips. The second approach (Figure 4) uses three times as many gates as my solution and requires an external clock, but otherwise appears to be equivalent.

Last modified: 8 March 2003