Gray code is a form of binary and the most popular absolute encoder output type. This white paper will explain Gray Code, discuss converting Gray Code to Natural Binary, explain how to use software to convert to gray code, and converting Gray Code to Natural Binary in PLC ladder logic.
Gray Code is a form of binary that uses a different method of incrementing from one number to the next. With Gray Code, only one bit changes state from one position to another. This feature allows a system designer to perform some error checking (i.e., if more than one bit changes, the data must be incorrect). Table 1 illustrates the difference between Natural Binary and Gray Code.
Gray Code is the most popular absolute encoder output type because its use prevents certain data errors that can occur with Natural Binary during state changes. For example, in a highly capacitive circuit (or sluggish system response), a Natural Binary state change from 0011 to 0100 could cause the counter/PLC to see 0111. This sort of error is not possible with Gray Code, so the data is more reliable. In Table 2, note that even from position 7 to 8, Gray Code only changes one bit state.
Table 1.
Table 2.
On paper, the process is easy:
1. Write the Gray Code and copy the left most bit under itself.
2. Add the copied bit to the next Gray Code bit to the right, drop all carries, and write result next to the copied digit from step 1. Remember, 0+0=0, 0+1=1, 1+0=1, 1+1=0.
3. Repeat step 2 until completed. See Table 3.
Table 3.
The process of using software to convert Gray Code is very straightforward. One way to convert Gray Code to binary is by means of a short software routine, such as the chart at right shows for a 10-bit encoder.
Table 4.
Here are the first few rungs starting with the MSB (most significant bit) or left most Gray Code bit shown in the Table 3 on previous page.
Notice that Rungs 2 and 3 are simply exclusive-OR circuits. The outputs of each of these Rungs will make up the Natural Binary code for all N bits. The PLC then converts this code into an integer for use elsewhere in the PLC program.
Table 5.
If you still have questions about Gray Codes, Natural Binary, or anything else encoder-related, give us a call. When you contact EPC, you talk to real engineers and encoder experts who can answer your toughest encoder questions. You’ll get the answers that make sense for your application.