Gray Codes

18,204

7

11

Introduction: Gray Codes

This instructable describes what gray codes are and when they should be used.  It also includes C source code that generates gray codes from 1 to 32 bits in length.

Definition:
A gray code is a number series in which one bit changes with each increment.

Here is a 2 bit gray code:
00
01
11
10

You may notice that it is different from the normal binary counting sequence:
00
01
10
11

In the normal binary counting sequence, when going from 01 to 10 (from 1 to 2 decimal) there are two bit changes, the first and the second bit change their state.  Two bit changes also occur when going from 11 to 00.

You may notice that only one bit changes at a time in the gray code sequence above.

So, why would we care whether there is only a single bit transition or whether there are multiple bit transitions?  It depends on the application...

Step 1: Example Use of Gray Codes

Example:
Here is an example where using the binary sequence gives us difficulties:

Suppose we wanted to read the position of a astronomical observatory Dome so we can be sure the dome opening is pointed so that the opening and the telescope are aligned. We could choose to read the position optically. We could print a strip of say eight black and white bars on the dome wall and read the dots using eight photoresistors. We could then read the position of the dome to within 1/256 of a full circle, or about 2 degrees.

See the emitter/detector circuit diagram below.  To 'read' the position of the dome the microprocessor such as an Arduino would read the black and white bars on the dome wall, i.e. that bars rotate with the dome and the stationary reader does not rotate.   The base of the 8 photodetectors are wired to 8 input pins of the Arduino.  What coding sequence should we use?

Now suppose we had used the normal binary counting sequence to create our black and white bars for our photoresistors to sense. The problem we run into using the binary counting sequence is when we transition between one number and the next. Lets say our sensors are moving between the '255' position and the '0' position. As the transition occurs and the photoresisters are in between both numbers, a photoresistor or two might transition from '1' to '0' a little before the others. This could be due to a slight offset in the photoresistor's position or may be due to slight variance in the photoresistor's construction/chemical composition making it a little more sensitive than the others. For whatever reason one or more will transition at a different time than the others. During this time the reading from the phototransitors may go from 255 to 127 then to 0. If the motion is slow enough one may see many of these spurrious transitions between most numbers.

GRAY CODE to the Rescue!
A better approach would be to use a gray code instead of the binary code. Using the gray code, only one bit of the code changes with each increment. Therefore when between two positions of the code only one bit may fluctuate between the two positions. Therefore when between positions 0 and 1, the photoresistors may sometimes read 0 and sometimes read 1, however, both answers are still very close the actual dome position.

The problem with gray codes is that the decimal value between one position and the next do not differ by one. Software can easily resolve this using an array which includes the gray code (or its inverse). One can use the value read in from the photoresistors as an index into an array. The value of the array is the decimal position. Using the array one can then calculate the difference in postions.

Step 2: Gray Code Source

How to Generate Gray Codes?
I have included a sample 'C' source code that generates gray codes for any number of bits between 1 and 32 bits in the included file

Attachments

Be the First to Share

    Recommendations

    • For the Home Contest

      For the Home Contest
    • Make It Bridge

      Make It Bridge
    • Big and Small Contest

      Big and Small Contest

    11 Comments

    0
    DeC12
    DeC12

    5 years ago

    Thanks maewert, great article. Alas the C code seems to be slightly mangled, doesn't compile because 2 of the for loops are partially missing:

    for (i=0;i gray_scale[i] = '0';

    for (index=1;index {

    I tried viewing page source but the code looks broken in the source, unfortunately I am not intelligent enough to guess what the missing code should be (just trying to make an absolute encoder).

    0
    maewert
    maewert

    Reply 5 years ago

    I corrected the code and attached it as a file instead to ensure it doesn't get mangled.

    Thanks!

    0
    DeC12
    DeC12

    Reply 5 years ago

    many thanks! just 2 compiler errors now (C is getting so darned picky about typing) -- wants the %8d in the printfs to be %8ld, easy peasy fix.

    I have been trying to wrap my head around the 2 kinds of gray code -- concentric rings vs single track. I visited http://www.piclist.com/techref/stgc.asp

    but am unable to figure out what the lists of integers represent.

    note also this handy link

    http://www.dgkelectronics.com/inkscape-optical-rot...

    to an inkscape extension that generates svg graphics for optical encoder purposes, including linear gray code. what I'm looking for now is code to generate the lookup table (optical sensor bitmask to rotational position). almost there... and if I have to, I can discover that table empirically (tedious but do-able)

    0
    steveastrouk
    steveastrouk

    12 years ago on Introduction

    Useful, for those faced with understanding Grey codes.

    Did you consider just servoing the dome position, based on the scope itself ? You could use IR sensors to track it.

    0
    maewert
    maewert

    Reply 12 years ago on Introduction

    Hey Steve,
    Telescopes are generally on polar mounts and therefore it can't be servo'd.  We can listen into the protocols and determine the telescope position and then convert that into Dome azimuth.  I haven't used this grey-code approach actually since there are other simpler methods but I thought I'd document the grey code for all those (ok, a whopping ~245 views!) who might want to know  :-)

    Thanks,

    Mark

    0
    steveastrouk
    steveastrouk

    Reply 12 years ago on Introduction

    My approach would just "watch" the end of the tube and move the dome to track it. Doesn't matter whether you have an Alt-az mount or an equatorial then.

    Steve

    0
    maewert
    maewert

    Reply 12 years ago on Introduction


    Oh yes, I see now.  I have heard of those.  IR transmitters on the tube and several receivers on the inside of the dome to determine the tube's orientation.  I haven't tried them myself but I did read where some users had them.  Some reported that they occasionally misidentify the tube orientation and spin the dome in crazy directions.  Sounds like it could work, though.  I am resisting using IR to keep the light pollution down inside the dome (the astronomical cameras can pick it up.)  I was going to use IR to read the position of the shutter (at least either fully open or fully closed) but then again I would have to drive the IR signal through an output pin so that I can disable the light after the reading and before any pictures are taken.
    Thanks for the ideas :-)

    Mark

    0
    steveastrouk
    steveastrouk

    Reply 12 years ago on Introduction

    I think it depends on your electronics. I am sure I could make a system that wouldn't spray stray light that would affect the camera.

    0
    tteedd
    tteedd

    Reply 7 years ago on Introduction

    It is amazing how a little stray light can affect views of astro objects. I have a 'goto' scope which has a red led display on the handset (they are all red as it does not affect your night sight to any great extent).

    It was not until I fitted a video camera and the video display turned pink when the handset display was on that I realised how much affect a little stray light had.

    0
    kelseymh
    kelseymh

    10 years ago on Introduction

    I completely missed this when you published it (I saw it after following up on your awesome mirror figure teststand).

    We used Gray codes in the data acquistion system for my previous particle physics experiment (BaBar). I came into the experiment late, and never had to deal with that stuff; the software (of course) gave us regular numbers.

    Thank you for the very clear explanation of what Gray coding is, and why it's useful! Even if the particular application has other solutions, it was an excellent pedagogical example.

    0
    maewert
    maewert

    Reply 10 years ago on Introduction

    Thank You for your kind words. In order to describe the benefits of grey codes I needed an example people could understand. A bit like describing a screwdriver to someone and explaining how it can be useful, especially one with a philips head.

    Where I work we often hire summer college students and one computer science student I worked with had no knowledge about using 'AND' and 'OR' to mask off and test bits within a variable. Seems you can be a Microsoft foundation class expert and not need to actually understand what happens under the hood. So sad for us. I created this grey scale instructable hoping in the future someone might 'rediscover' such knowledge lost. :-)

    I'm so glad many young people have found Instructables and we can (hopefully!) pass on some knowledge before even we forget!