AutomateDirectUSAMotion LibraryIndustrial monitors & PCs

How-to

Decoding a 9-bit Gray Code Encoder for Travel Distance

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

Short answer

A 9-bit single-turn Gray encoder gives 512 counts per revolution, 0.703125 degrees each. Decode the Gray word with a four-step XOR-shift cascade, accumulate the wrap-corrected delta between samples into one running total, and scale that total by the travel per encoder revolution. The correction holds while the shaft moves less than half a revolution between samples; beyond that, sample faster or re-home.

On this page
  1. What the nine bits give you
  2. Read the bits as one word
  3. Decode Gray to binary with the XOR cascade
  4. Accumulate revolutions and scale to distance
  5. Limits and where each number comes from
  6. Bench checks before you trust the number
  7. The decision
  8. Questions asked

A 9-bit single-turn Gray-code encoder gives you 512 counts per revolution, and a travel-distance measurement needs three moves: decode the Gray word to binary, accumulate the wrap-corrected change between samples into one running total, and scale that total by the mechanical travel per encoder revolution. The decode is a four-step XOR-shift cascade, not a bit-to-numeric block. The wrap correction is valid while the shaft moves less than half a revolution between samples, so your sample period sets the speed limit. The steps below start where reading a Gray code absolute encoder into a PLC leaves off: the nine bits are in the input image, and you want a distance you can trust.

What the nine bits give you #

Nine bits make 2^9 = 512 steps per revolution, so one count is 360/512 = 0.703125 degrees of shaft rotation. Gray code changes exactly one bit between adjacent positions, including across the wrap, where Gray 100000000 becomes 000000000. Natural binary flips all nine bits at that same boundary, so skewed inputs would sample a random mixture. With Gray, a word caught mid-transition reads as the old or the new position, which is why a raw sample is at most one count wrong.

That guarantee belongs to the word, not to single bits: take all nine in the same scan, from one input group or one input word. The encoder is also single-turn, so the code repeats every revolution; travel longer than one shaft revolution has to be counted in software.

Read the bits as one word #

  1. Map the nine inputs into one word with bit 0 as the LSB and bit 8 as the MSB, matching the pin assignment in the encoder datasheet. If the input card already delivers the bits as a word, mask it with 16#1FF to drop the unused bits.
  2. Copy that word once per scan, before any math, so every later step works on the same sample. Bits scattered over several terminals belong in one input group first; the practice is the one in wiring a 10-bit Gray code absolute encoder to standard DC inputs.
  3. Leave bit swapping alone until the decode tests below pass or fail; swapping bits until the numbers look right hides a wiring-order error instead of fixing it.

Decode Gray to binary with the XOR cascade #

The rule, with bit 8 as the MSB: the top binary bit equals the top Gray bit, and every lower binary bit is the XOR of its own Gray bit with the binary bit above it, from b7 = b8 XOR g7 down to b0 = b1 XOR g0. Run as shifts, the rule collapses into four steps. In IEC 61131-3 structured text, SHR is the standard shift-right function and XOR the standard operator; raw_word, gray and bin are example variables of mine, all UINT, with raw_word holding the masked input word:

gray := raw_word AND 16#1FF;
bin  := gray;
bin  := bin XOR SHR(bin, 1);
bin  := bin XOR SHR(bin, 2);
bin  := bin XOR SHR(bin, 4);
bin  := bin XOR SHR(bin, 8);
bin  := bin AND 16#1FF;   (* decoded, 0 to 511 *)

Four steps cover up to 16 bits, so nine bits sit inside their range. In ladder, run the XOR and shift-right instructions in the same order, or nine single-bit XOR rungs that follow the rule; a mistyped rung or a wrong bit order fails the way why a Gray code to binary ladder conversion counts wrong describes.

The test that proves the code: set raw_word to 16#0002, the Gray word for decimal 3, and bin must read 3; set it to 16#0100, Gray 100000000, and bin must read 511. Run the decode every scan, before the position math.

Accumulate revolutions and scale to distance #

  1. Sample bin at a fixed period in a periodic task, and keep the previous sample.
  2. Subtract the previous sample from the new one as a signed value.
  3. Correct the wrap: if the difference is greater than 256 counts, subtract the counts in one revolution; if it is less than negative 256 counts, add them.
  4. Add the corrected difference to a running total held in retentive memory.
  5. Scale the total: distance equals the total times the travel per encoder revolution, divided by the counts in one revolution.

The variables: delta is INT, total a retentive DINT, last_bin UINT, distance_mm and mm_per_rev REAL, with mm_per_rev set from the mechanics (5.0 for the worked example, a screw of 5 mm pitch directly coupled to the shaft):

delta := bin - last_bin;      (* signed 16-bit subtraction *)
IF delta > 256 THEN
    delta := delta - 512;
ELSIF delta < -256 THEN
    delta := delta + 512;
END_IF;
total := total + delta;
last_bin := bin;
distance_mm := total * mm_per_rev / 512.0;

The correction is right only while the shaft moves less than 256 counts between samples: at or beyond half a revolution, the true move and its mirror image look identical to the program. If the total runs backwards when the machine moves forward, negate delta in software, or use the encoder's direction input if its datasheet lists one. For shaft angle instead of distance, the count scales to degrees exactly as in scaling a 262144-count absolute encoder to 0-360 degrees, because encoder angle scaling uses 360 degrees per revolution at any bit count.

Worked example #

Inputs: travel per encoder revolution 5 mm, sample period 4 ms, shaft speed 300 rpm. Everything below is a calculated example for those inputs, not a measured result.

  • Speed limit: 0.5 rev / 0.004 s = 125 rev/s = 7500 rpm, so 300 rpm sits far inside it. Per sample the shaft covers 300/60 × 0.004 = 0.02 rev, which is 10.24 counts.
  • Resolution at the load: 5 mm / 512 counts = 0.009765625 mm per count.
  • Crossing the wrap: the decoded count goes from 509 to 2. The difference is 2 - 509 = -507, corrected to -507 + 512 = +5 counts, so the total rises by 5 and the distance grows by 5 × 0.009765625 = 0.048828125 mm.

Limits and where each number comes from #

Quantity Value or limit Where it comes from
Steps per revolution 512, giving 0.703125 deg per count 2^9; encoder nameplate and datasheet
Code property One bit changes per step, including the wrap Gray code; confirm against the datasheet code table
Bit order and count direction MSB and LSB pin assignment; which way the count rises Datasheet pin table
Max change per sample Below 256 counts Half the counts in one revolution; derived
Max shaft speed Below 0.5 rev divided by the sample period Derived; sample period from the periodic task
Error from input skew 1 count on a same-scan word Property of Gray code
Travel per encoder revolution Machine-specific Mechanical drawing or gear data

Bench checks before you trust the number #

  1. With the two decode tests passing, turn the shaft slowly through one revolution and watch the raw word: exactly one bit must change per step. Two bits changing together point to wiring, bit assignment, or an output that is not Gray.
  2. Verify the remaining test vectors: Gray 0 must decode to 0 and Gray 000000110 to 4.
  3. Cross the wrap in both directions at slow speed; the total must continue without a jump of about one revolution of counts.
  4. Jog at the highest working speed and compare the accumulated distance with a measured move. A short or erratic total means the sample period is too long for that speed. Run the jog with the guard in place and under the machine's risk assessment; nothing in this measurement is worth defeating an interlock.
  5. Expect the decoded value to flicker by one count at rest; that is transition sampling and normal. Larger jumps mean the bits were read in different scans or one input is miswired.

The decision #

If the travel never leaves one shaft revolution, a rotary table for example, skip the accumulation and scale the decoded count directly. If the travel runs across many revolutions and the shaft stays below the speed limit, decode with the four-step cascade, accumulate the wrap-corrected differences in a periodic task, and scale by the travel per revolution; the result then holds to one count of skew error plus the accuracy of your mechanics. If the shaft outruns the limit at your shortest practical period, or the axis can move half a revolution or more while powered off, fit a multi-turn encoder and configure its word instead, as covered in configuring the Gray decode of a multi-turn absolute encoder, or add a home switch and re-home at every start-up.

Questions asked

How do I recover the travel total after a power cycle?

At start-up, reduce the retentive total modulo the counts in one revolution to get the last count the program saw, then run the same wrap correction between that value and the live decoded count. This works only if the shaft moved less than half a revolution while the power was off. If it may have moved farther, the correction can pick the wrong direction, so re-home the axis before trusting the total.

Why must all nine inputs be read in the same scan?

Gray code's one-count guarantee belongs to a word sampled at one instant. Bits copied in different scans can blend the old position with the new one, and the blend can decode to a value far from either. Wire the nine bits into one input group, copy the word once per scan, and decode only that copy.

Can I read shaft angle in degrees instead of travel in millimetres?

Yes: multiply the accumulated total by the degrees-per-count factor and you get shaft rotation since start-up, over as many revolutions as you have counted. It is shaft angle, not load angle; when the encoder is geared to the load, apply the gear ratio before calling it the load's position.

Can I get finer distance resolution from this encoder?

Resolution is the travel per encoder revolution divided by the counts in one revolution, roughly 0.0098 mm on the example screw. To refine it, gear the encoder so it turns faster than the load, which raises the counts per millimetre of load travel. The shaft then spins faster too, so recheck the speed limit for the new ratio before running.

Keep reading

  • Troubleshooting

    Why a Gray Code to Binary Ladder Conversion Counts Wrong

    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.

    Sensors, encoders and machine vision on the machine

  • Explainer

    Reading a Gray Code Absolute Encoder Into a PLC

    A five-line NPN absolute encoder needs no interface module: wire its five open-collector outputs to ordinary DC input points, read all five bits as one word each scan, and convert Gray code to binary before using the number. The catch is speed — scan-based sampling tracks a 32-position shaft reliably only below roughly half a revolution per second, so continuous multi-turn conveyor tracking belongs on a quadrature encoder and a high-speed counter with a home reference.

    Sensors, encoders and machine vision on the machine

  • Explainer

    Turning a Single-Turn Absolute Encoder Into Multi-Turn Position

    A single-turn absolute encoder can serve as multi-turn position feedback only while something else tracks shaft revolutions. Count rollovers in software while speed times the worst update gap stays below half a revolution, keep the whole counting chain powered or hold the axis with a brake, decode a travel-zone switch on limited travel, or gear a second single-turn encoder to the shaft with its reduction below the encoder's resolution. If unpowered shaft movement is possible and a reference move is not, use a true multi-turn encoder.

    Sensors, encoders and machine vision on the machine