gray code to binary conversion
Bill Kingsley
Posts: 11
Does anyone have some code for Gray code to binary conversion? I have a 12 bit rotary encoder that outputs gray code in parallel. I input this to 2 74HC165 shift registers then serialy load to the BS2 in a 16 bit word variable. I need a routine to convert the 16 bit Gray code to binary.
Thanks,
Bill
Thanks,
Bill
Comments
Sorry, I don't have a code snippet handy, but here is the method:
http://www.shef.ac.uk/physics/teaching/phy107/solvegray.html
I suspect the resident math guru, Dr. Tracy Allen, may have a simple answer for you as soon as he sees your question.
Regards,
Bruce Bates
With that I wrote the attached program.· It works with 4-bit variables, and can easily be modified to work with your data.
Update: After looking at the URL Bruce provided, I updated my program a bit to follow that algorithm (uses + instead of ^).· The result is the same and expect it will work·a bit faster for large values.·
Updated again with Tracy's Binary to Gray technique that doesn't require a loop.
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Jon Williams
Applications Engineer, Parallax
Dallas Office
Post Edited (Jon Williams) : 12/18/2004 2:21:40 PM GMT
Good to see you around again! I do have bit of a writeup at this URL: www.emesystems.com/BS2fsm.htm#Gray%20code
It is essentially the same as Jon's program.
A 16 bit code follows the same pattern:
You might want to take a look at Art of Electronics, as there is a cute circuit there using XOR gates and a funny story.
The conversion from binary to Gray code is much easier, and does not require a loop, just XOR the binary word with itself, shifted one right:
graycode=(binary>>1) ^ binary
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Tracy Allen
www.emesystems.com
0 ^ 0 = 0 ... 0 + 0 = 0
0 ^ 1 = 1 ... 0 + 1 = 1
1 ^ 0 = 1 ... 1 + 0 = 1
1 ^ 1 = 0 ... 1 + 1 = 0 (bit that carried is lost)
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Jon Williams
Applications Engineer, Parallax
Dallas Office
There is a carry from the sum of two bits only when both bits are one.
A full adder allows the sum of three bits (one of which is usually the carry from the previous column). The sum bit is simply the XOR of all three, and there is a carry if any two bits are ones. The maximum value is of course %1+%1+%1 = %11
SUM1 = A1 XOR B1 XOR Carry0
Carry1 = (A1 AND Carry0) OR (B1 AND Carry0) OR (A1 AND B1)
The full adder in hardware takes two half adders, one more XOR, one more AND and one three-input OR gate.
The circuit in Art of Electronics shows how to implement both the Gray->binary and binary->Gray conversions using only XOR gates. Those are static logic circuits (except for propation delays), but I don't see how to do it without a loop on the Stamp. The FOR-NEXT structure is slow on the Stamp--so you could simply repeat the code for each bit. Jon also pointed out to that the index logic is slow. Something using shifts and mask logic might be faster, but, you don't need it, so why push it?
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Tracy Allen
www.emesystems.com