Encoder with gray code to decimal

More
10 years 6 months ago #72784 by emcPT
Hello,

I need to use a absolute gray code encoder with 10 bits. Looking for information on gray code and linuxcnc I found a component that is called gray2bin that converts a u32 to u32.

My first question is to understand if is needed to use a gray code to a "decimal like" value to be used as a u32, correct?
For example the gray code:

bit 9 1
bit 8 1
bit 7 1
bit 6 0
bit 5 1
bit 4 0
bit 3 1
bit 2 1
bit 1 1
bit 0 1

should be converted to the number 1110101111 to be the input of the gray converter?
If so, is the u32 type capable of holding such a big number?
EDIT: Yes it is:
u32 - a 32 bit unsigned integer, legal values are 0 to 4,294,967,295

Thank you

Please Log in to join the conversation.

More
10 years 6 months ago #72786 by andypugh
Yes, gray2bin works with up to 32 bits.

Please Log in to join the conversation.

More
10 years 6 months ago #72839 by jtc
Based on gray2bin source code we are trying to implement this conversion on our custom hal component, but without sucess...

the relevant part of code is this:
Code:
int gray_to_decimal(bool bit0, bool bit1, bool bit2, bool bit3, bool bit4, bool bit5, bool bit6, bool bit7, bool bit8, bool bit9) { unsigned int in = 0; unsigned int out = 0; unsigned int mask; unsigned int binary; in = bit0 + bit1*10 + bit2*100 + bit3*1000 + bit4*10000 + bit5*100000 + bit6*1000000 + bit7*10000000 + bit8*100000000 + bit9*1000000000; binary = in; for(mask = in >> 1 ; mask != 0 ; mask = mask >> 1) { binary ^= mask; } return binary; }

with the following bits:

Attachment not found



the result is:
15670030.0


that is clearly wrong as a binary number is expected. The correct result should be: 11111100

What I am doing wrong?

Please Log in to join the conversation.

More
10 years 6 months ago #72840 by andypugh

jtc wrote:

Code:
in = bit0 + bit1*10 + bit2*100 + bit3*1000 + bit4*10000 + bit5*100000 + bit6*1000000 + bit7*10000000 + bit8*100000000 + bit9*1000000000;


This is wrong.

You want to multiply by binary constants. This _might_ work or will give a compiler error
Code:
in = bit0 + bit1*0b10 + bit2*0b100 + bit3*0b1000 + bit4*0b10000 + bit5*0b100000 + bit6*0b1000000 + bit7*0b10000000 + bit8*0b100000000 + bit9*0b1000000000;

However, what I would do is the fractionally more efficient:
Code:
in = bit0 + bit1<<1 + bit2<<2 + bit3<<3 + bit4<<4 + bit5<<5 + bit6<<6+ bit7<<7 + bit8<<8 + bit9<<9;

Please Log in to join the conversation.

More
10 years 6 months ago #72847 by jtc
Thank you! with the last solution it works :)

Please Log in to join the conversation.

Time to create page: 2.968 seconds
Powered by Kunena Forum