PDF Electric and Supply
Supplier of New and Reman GE Fanuc and Allen Bradley PLC parts
PDF Electric and Supply
PLC Programming Handbooks
The Black and White of Gray Code
Gray code (named after it's inventor Frank Gray) is a sequence of binary numbers where only one bit changes at a time. Marching through the integer sequence then only requires flipping one bit at a time which in certain applications drastically reduces any errors. In standard binary many digits can change at once, for instant when going from 7 to 8 (0111 to 1000) there are four bits changing state.
It's a fact of life that a PLC input can turn ON quicker then it can turn OFF. We're talking milliseconds here but with equally fast scan times it can generate a wrong reading when using normal binary methods. With Gray code you can be assured that only one bit is going to change. Anymore then that one bit changing and there is something wrong.
The problem is demonstrated in the figure below. For example, let's say it takes an input signal 300 milliseconds to come ON but it takes 500 milliseconds to go OFF. In binary then when going from 7 to 8 the ON bit will come on first but the bits that are ON are still ON and therefore the decimal value is 15. It takes another 200 milliseconds for the ON bits to go OFF and achieve our proper reading of eight. On the other hand, with Gray code notice that only one bit is changing from OFF to ON and therefore there is no error.
Here's how the sequence in Gray code starts and you can compare how different it is to standard binary code. I've made it easy by emphasizing the bits that are changing.
Another neat trick is you'll notice that going from 15 to 0 still preserves our Gray code of only changing one bit. Pretty neat, eh? This is why they call it a cyclic code because it can go around in circles.
What is Gray Code good for?
In automation it's particularly good for position transducers used to measure the angle of a shaft. This application benefits from the cyclic nature of Gray codes, because the first and last values of the sequence are different by only one bit. That is, if you feel like going round and round in circles.
In an optical absolute encoder there is a disk with a Gray code pattern like so...
A beam of light, LED or laser, is shot through the disk and the light is picked up on the other side by a gang of phototransistors. This light is converted into electrical signals which can be read as Gray code or converted to BCD. As the shaft (and therefore the disk) rotate the light coming through the holes changes but only slightly based on the Gray code. Thus the controller reading the phototransistors knows the exact position of the shaft.
Illustration: Example of an absolute encoder converting light to a Gray code.
Advanced Topic: Using Ladder Logic for Gray code conversion