AutomateDirectUSAMotion LibraryIndustrial monitors & PCs

Troubleshooting

Why a Gray Code to Binary Ladder Conversion Counts Wrong

Sensors, encoders and machine vision on the machine Published 10 min read By AutomateDirectUSA engineering team

Short answer

A Gray code to binary ladder conversion counts wrong when each XOR rung is fed the previous Gray bit instead of the previous binary bit, or when the nine input bits are mapped in a crossed order. Decode from the top bit down: copy the most significant bit, then take every lower bit as the exclusive-OR of the binary bit above it and the Gray bit at the same position. On a 9-bit, 512-step encoder the result must run 0 to 511, step by one.

On this page
  1. Why does a Gray code absolute encoder count wrong in ladder logic?
  2. What does the raw integer look like before the decode?
  3. What is the correct Gray-to-binary cascade for a 9-bit encoder?
  4. How do I check the nine inputs before blaming the decode?
  5. How do I build the conversion rung by rung and pack the result?
  6. What should the decoded value do on a healthy revolution?
  7. How many degrees is one count on a 512-step encoder?
  8. Which faults survive a correct conversion?
  9. Questions asked

A Gray code absolute encoder that counts wrong in ladder almost never has a bad encoder behind it: the XOR cascade is being fed the previous Gray bit instead of the previous binary bit, or the nine input bits sit on the inputs in a crossed order. Decode from the top bit down, confirm that exactly one input changes per step, and expect the decoded value to step by one through 0 to 511 and wrap once per revolution. The checks below run in the order cheapest to execute, with the arithmetic for a 9-bit single-turn absolute encoder shown in full.

Why does a Gray code absolute encoder count wrong in ladder logic? #

Almost every wrong count traces to the decode itself: the ladder cascade feeds each XOR with the previous Gray bit instead of the previous binary bit, or the nine input bits land on the PLC inputs in a crossed order — the wiring and the encoder are usually fine.

Gray code exists for exactly this reason: adjacent positions differ in a single bit, so a controller that samples while a transition is in flight is never more than one count off. Plain binary has no such property. Going from 255 to 256 flips all nine bits at once (011111111 becomes 100000000), and a sample taken mid-change can land anywhere between the two values — for that one transition, up to 129 counts away from the truth. That is why the encoder transmits Gray and why the PLC must decode it before treating the number as a position.

Most ladder environments ship no native Gray-to-binary block, so the program builds the conversion from contacts and coils, and that construction is where both failure modes live: the cascade fed from the wrong reference bit, or the physical encoder bits mapped onto the wrong inputs. Getting the nine signals into the controller in the first place is the subject of reading a Gray code absolute encoder into a PLC; everything below starts from the point where the bits have arrived and the integer is still wrong.

What does the raw integer look like before the decode? #

Reading the nine inputs straight into an integer produces a valid number that is not position: at the low end it walks 0, 1, 3, 2, 6, 7, 5, 4 — single steps up and down, then jumps that grow as the higher bits join.

The sequence is the fingerprint of a missing decode. The packed integer is the Gray codeword read as weighted binary, so it steps up, steps down, then leaps 128 counts at the half-revolution carry. At low shaft speed the walk looks close enough to monotonic to pass a bench check, which is why the fault survives commissioning and reappears later as position jumps, a homing move that lands short, or an axis that stops a step early.

No amount of input filtering, scan slowing or averaging fixes it. The encoder is speaking Gray and the program is listening in binary; smoothing the electricity does not translate the language. If the packed integer reproduces that walk, the input layer is healthy and the missing piece is the decode in the next section.

What is the correct Gray-to-binary cascade for a 9-bit encoder? #

Decode from the top down: copy the most significant bit, then make every lower binary bit the exclusive-OR of the binary bit above it and the Gray bit at the same position — B7 = B8 XOR G7, continued bit by bit down to B0.

In symbols, with G8 the encoder's most significant output and B8 through B0 the nine binary result bits:

B8 = G8
B7 = B8 XOR G7
B6 = B7 XOR G6
B5 = B6 XOR G5
B4 = B5 XOR G4
B3 = B4 XOR G3
B2 = B3 XOR G2
B1 = B2 XOR G1
B0 = B1 XOR G0

Solve the rungs top-down within one scan, so each coil is computed from the bit above it already updated this scan. The error that produces a plausible but wrong number is feeding each XOR with the adjacent Gray bit instead — starting the chain with the exclusive-OR of two encoder outputs. That version decodes correctly at some shaft positions and drifts by tens of counts at others, which is the intermittent, position-dependent fault that sends people chasing wiring that is not broken.

The chain length follows the resolution: a 10-bit encoder adds one rung at the top, a 13-bit encoder adds four, and nothing about the structure changes.

How do I check the nine inputs before blaming the decode? #

Turn the shaft slowly and watch the nine inputs: exactly one must change per step, so a bit that never toggles, or a step where two inputs move together, is a wiring or level fault to clear before touching any logic.

Run the four checks in order; each takes minutes and each result points at a different layer:

  1. One bit never toggles. Measure the voltage at that input terminal with the shaft turning. A constant level means the encoder's output stage and the input bank disagree on sinking versus sourcing, or the input common is missing — the same level-matching job described in wiring a 10-bit Gray code absolute encoder to standard DC inputs.
  2. Two bits move on one step. A crossed pair or a bouncing marginal input. Swap the two bit assignments in the I/O map: if the fault moves with the wires, correct the map; if it stays with the bit, measure that input's level and filter time.
  3. Errors grow with speed. Check the cable shield terminated at one end and the input filter setting against the toggle-rate arithmetic in the final section.
  4. Every bit toggles once per step and the integer still walks the Gray pattern. The electrical layer is proven; stop measuring and go fix the decode.

One more standing check while the shaft turns slowly: exclusive-OR each input sample against the previous scan's sample. A healthy encoder shows exactly one set bit in that comparison; a zero result means a sample was missed or repeated, and two or more set bits mean a doubled or crossed transition. The write-up on detecting single-step misses in Gray code encoders via PLC XOR turns this comparison into a permanent diagnostic rung.

How do I build the conversion rung by rung and pack the result? #

Write one copy rung and eight exclusive-OR rungs, solve them top-down in the same scan, and pack the nine result bits into an unsigned integer with the lowest bit at the least significant position — the register then holds decoded position, ready for scaling.

  1. Write the bit map first. Note which physical input each encoder output, G0 through G8, lands on before any rung exists; a crossed pair then becomes a one-line fix instead of a mystery.
  2. Snapshot the inputs. Copy all nine inputs into nine memory bits at the top of the scan and build the cascade from those copies. Bits read at different moments in the scan are the classic cause of a one-count error that wanders.
  3. Rung one is a copy: a normally open contact on the top Gray memory bit drives the top binary coil.
  4. Each lower bit gets two parallel branches driving its coil — the higher binary contact in series with the inverted Gray contact, and the inverted higher binary contact in series with the Gray contact. Solve from the bit under the top down to the last, in order, so every coil sees the updated bit above it.
  5. Pack the nine result bits into an unsigned integer with the PLC's bit-collection instruction, lowest bit at the least significant position. The register now holds the raw position, and it reads 0 to 511.

Name the nine memory bits in the documentation that travels with the program, not just in rung comments: when this file is reopened in three years, the bit map is the first thing nobody remembers.

What should the decoded value do on a healthy revolution? #

A correct conversion steps by exactly one count in one direction through the whole revolution, crosses 511 to 0 once, and returns to the same value after a power cycle with the shaft untouched — anything else locates a fault before hardware gets touched.

Confirm the low bits against the reference sequence; the same pattern repeats in every block of eight counts across the full range:

Position Gray code Binary
0 000 000
1 001 001
2 011 010
3 010 011
4 110 100
5 111 101
6 101 110
7 100 111

Turn the shaft slowly through the first positions, watch the Gray inputs against the middle column, then the decoded integer against the right column; one slow revolution condemns or clears the decode.

Two results look wrong and are not. A value that steps opposite to the machine's convention is an encoder mounted counting backward — invert it in software by subtracting the reading from 511 instead of rewiring. A value that is correct but displaced by a fixed amount from machine zero is the encoder's mechanical index; store the offset and subtract it, letting the result wrap at full scale.

The power-cycle check is the payoff of absolute feedback: shaft untouched, the decoded value must be identical after a full power-down. If it is not, the fault is in sampling or decode, not in the encoder.

How many degrees is one count on a 512-step encoder? #

One count on a 512-step single-turn encoder is 360 divided by 512, which is 0.703125 degrees, and the decoded integer times that factor is the shaft angle — for the example decode below, 300 counts is 210.9375 degrees.

Worked example, one sample from a 9-bit single-turn encoder reporting the Gray pattern 110111010:

  • Cascade from the top: B8 = 1; B7 = 1 XOR 1 = 0; B6 = 0 XOR 0 = 0; B5 = 0 XOR 1 = 1; B4 = 1 XOR 1 = 0; B3 = 0 XOR 1 = 1; B2 = 1 XOR 0 = 1; B1 = 1 XOR 1 = 0; B0 = 0 XOR 0 = 0.
  • Binary result: 100101100, which is 256 + 32 + 8 + 4 = 300 counts.
  • Shaft angle: 300 × 360 / 512 = 108000 / 512 = 210.9375 degrees.

The same inputs through the wrong cascade — each XOR fed with the adjacent Gray bit — produce 101100111, which is 256 + 64 + 32 + 4 + 2 + 1 = 359 counts, scaling to 359 × 0.703125 = 252.421875 degrees. That is 59 counts, about 41.5 degrees of error at this position while neighboring positions decode fine: the signature that wastes the most diagnostic hours, because it looks like a marginal connection rather than a logic typo.

For integer-only controllers, multiply before dividing in a 32-bit register: computing thousandths of a degree means multiplying the count by 360000 before dividing by 512, and the full-scale intermediate is about 184 million, well inside the roughly 2.1 billion a signed 32-bit register holds.

Which faults survive a correct conversion? #

A count that still misbehaves points at sampling and speed: a one-count jump at isolated transitions is normal Gray sampling ambiguity, while large or intermittent jumps mean bits sampled in different scans, filter time too long, or a marginal level.

Match what remains against this list and act on the decision in each line:

  • A one-count jump at isolated transitions. Normal sampling, not a fault: a read taken on a transition can land on either neighbor. Deadband or average consecutive reads if the application minds.
  • Correct near zero, wrong above it. Upper inputs not wired, or the cascade stops short of the top bit. Restore the missing rungs and map entries.
  • Wrong by tens of counts at some positions, right at others. The cascade XORs adjacent Gray bits. Rewrite every rung so each XOR takes the binary bit above it.
  • The same wrong number after every power cycle at the same physical position. A constant offset. Store it and subtract, wrapping at full scale.
  • Errors that appear only as speed rises. Check the timing budget. The fastest-changing output is the first bit, which switches every two steps: at 2 revolutions per second that is 512 toggle events per second, with roughly a millisecond between a change and its return. The input response and the scan must sit well inside that window, and a scan that intends to see every step must beat 1024 steps per second at that same speed.

That last line is the real decision. Ladder decoding is the right tool while the scan comfortably beats the step rate and the application tolerates a one-count sampling uncertainty; when the shaft outruns the scan, the job moves to hardware that latches the code between scans — the comparison drawn in which absolute encoder interface works with a high-speed counter PLC.

Questions asked

Does a 13-bit Gray code encoder need a different conversion?

No, the cascade is identical and just four rungs longer. A 13-bit single-turn encoder decodes to a value from 0 through 8191, and the scaling factor becomes 360 divided by 8192, which is 0.0439453125 degrees per count. Only the top bit position and the scaling change; the exclusive-OR structure and the top-down solving order stay the same.

Why does the decoded value flicker when the shaft rests on a transition?

It should never flicker by more than one count. Gray code guarantees that a sample taken while one bit is changing lands on one of the two adjacent codes, so a parked shaft can only waver between neighboring positions. Wider flicker means two bits are moving together, which points back to a crossed wire, a marginal input level, or bits sampled in different scans.

Can the same ladder decode a Gray code linear scale?

The cascade is identical, but the scaling is not. A linear scale converts counts to distance with the pitch stated in that scale's datasheet, not with 360 degrees divided by the step count. Decode the bits the same way, multiply the binary result by the documented distance per count, and remember that the wrap from maximum back to zero applies only to rotary single-turn units.

How do I test the decode without an encoder on the bench?

Force the nine Gray memory bits to the patterns from the reference sequence instead of turning the shaft. Step through the forced patterns one at a time and watch the decoded integer; it must advance by exactly one per step and land on the matching binary value. This proves the logic alone and separates a program fault from a wiring fault without any hardware.

Keep reading

  • Explainer

    What it takes to read an absolute encoder into discrete PLC inputs

    Yes — a bit-parallel absolute encoder connects directly to discrete PLC inputs, with no special card, once four checks pass: output voltage matches the input card, one input is free for every bit, the logic converts Gray code to binary where needed, and the shaft stays under the scan-time speed limit. Networked Ethernet or Modbus encoders need documented protocol support in the PLC first.

    Sensors, encoders and machine vision on the machine

  • Selection guide

    Absolute encoder input card response time vs count rate

    Keep the 3-9 ms DC input card. Gray code changes one bit per count, so at a 10 ms count rate each input holds its level for two counts, 20 ms, against a 9 ms worst-case delay, and no transition is lost. The lag to budget is card delay plus PLC scan, about one to three encoder counts, which cam-switch replacement tolerates; the 0.8 ms card buys less than one count, so it is not worth a PLC family change.

    Sensors, encoders and machine vision on the machine

  • Troubleshooting

    Why a parallel absolute encoder shows no count on a PLC card

    A parallel absolute encoder has no pulse output: it presents the shaft position as a 25-bit binary word across individual PNP lines, so any counter or high-speed input waiting for edges shows zero. The cure is to match the card's input common to PNP sensing, prove each bit at the connector and at the card, and read all the bits together as one unsigned value.

    Sensors, encoders and machine vision on the machine