Микроконтролери и електроника
http://mcu-bg.com/mcu_site/

Проблем с разчитане на код на Грей
http://mcu-bg.com/mcu_site/viewtopic.php?f=4&t=3134
Страница 1 от 2

Автор:  sthx [ Вто Окт 24, 2006 6:19 pm ]
Заглавие:  Проблем с разчитане на код на Грей

Падна ми се следния ребус - абсолютен енкодер с код на Грей. С процесора трябва бързо да го прехвърля в нормално число. Кодът е непълен - 13-битов е, а числата са към 2000. Друга информация нямам, като изключим, че съм снел една редица от точки, но за сега не мога да открия закономерност. Поради липса на време за обработка не мога да обработвам данните като пълна таблица. Ако някой се е срещал с подобна гатанка, нека помогне. Благодаря предварително за съветите.

Автор:  zaphod [ Вто Окт 24, 2006 8:05 pm ]
Заглавие: 

Изображение
това са XORове

Автор:  VSU [ Вто Окт 24, 2006 8:41 pm ]
Заглавие: 

A Gray code represents each number in the sequence of integers
{0...2^N-1} as a binary string of length N in an order such that
adjacent integers have Gray code representations that differ in only
one bit position. Marching through the integer sequence therefore
requires flipping just one bit at a time. Some call this defining
property of Gray codes the "adjacency property" [8].

Example (N=3): The binary coding of {0...7} is {000, 001, 010, 011,
100, 101, 110, 111}, while one Gray coding is {000, 001, 011, 010,
110, 111, 101, 100}. In essence, a Gray code takes a binary sequence
and shuffles it to form some new sequence with the adjacency
property. There exist, therefore, multiple Gray codings for
any given N. The example shown here belongs to a class of Gray
codes that goes by the fancy name "binary-reflected Gray codes".
These are the most commonly seen Gray codes, and one simple
scheme for generationg such a Gray code sequence says, "start with
all bits zero and successively flip the right-most bit that produces
a new string."

Hollstien [9] investigated the use of GAs for optimizing functions of
two variables and claimed that a Gray code representation worked
slightly better than the binary representation. He attributed this
difference to the adjacency property of Gray codes. Notice in the
above example that the step from three to four requires the flipping
of all the bits in the binary representation. In general, adjacent
integers in the binary representaion often lie many bit flips apart.
This fact makes it less likely that a MUTATION operator can effect
small changes for a binary-coded INDIVIDUAL.

A Gray code representation seems to improve a mutation operator's
chances of making incremental improvements, and a close examination
suggests why. In a binary-coded string of length N, a single
mutation in the most significant bit (MSB) alters the number by
2^(N-1). In a Gray-coded string, fewer mutations lead to a change
this large. The user of Gray codes does, however, pay a price for
this feature: those "fewer mutations" lead to much larger changes.
In the Gray code illustrated above, for example, a single mutation of
the left-most bit changes a zero to a seven and vice-versa, while the
largest change a single mutation can make to a corresponding binary-
coded individual is always four. One might still view this aspect of
Gray codes with some favor: most mutations will make only small
changes, while the occasional mutation that effects a truly big
change may initiate EXPLORATION of an entirely new region in the
space of CHROMOSOMEs.

The algorithm for converting between the binary-reflected Gray code
described above and the standard binary code turns out to be
surprisingly simple to state. First label the bits of a binary-coded
string B[i], where larger i's represent more significant bits, and
similarly label the corresponding Gray-coded string G[i]. We convert
one to the other as follows: Copy the most significant bit. Then
for each smaller i do either G[i] = XOR(B[i+1], B[i])---to convert
binary to Gray---or B[i] = XOR(B[i+1], G[i])---to convert Gray to
binary.

One may easily implement the above algorithm in C. Imagine you do
something like

typedef unsigned short ALLELE;

and then use type "allele" for each bit in your chromosome, then the
following two functions will convert between binary and Gray code
representations. You must pass them the address of the high-order
bits for each of the two strings as well as the length of each
string. (See the comment statements for examples.) NB: These
functions assume a chromosome arranged as shown in the following
illustration.

index: C[9] C[0]
*-----------------------------------------------------------*
Char C: | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
*-----------------------------------------------------------*
^^^^^ ^^^^^
high-order bit low-order bit

C CODE
/* Gray <==> binary conversion routines */
/* written by Dan T. Abell, 7 October 1993 */
/* please send any comments or suggestions */
/* to dabell@quark.umd.edu */

void gray_to_binary (Cg, Cb, n)
/* convert chromosome of length n+1 */
/* from Gray code Cg[0...n] */
/* to binary code Cb[0...n] */

allele *Cg,*Cb;
int n;
{
int j;

*Cb = *Cg; /* copy the high-order bit */
for (j = 0; j < n; j++) {
Cb--; Cg--; /* for the remaining bits */
*Cb= *(Cb+1)^*Cg; /* do the appropriate XOR */
}
}

void binary_to_gray(Cb, Cg, n)
/* convert chromosome of length n+1 */
/* from binary code Cb[0...n] */
/* to Gray code Cg[0...n] */

allele *Cb, *Cg;
int n;
{
int j;

*Cg = *Cb; /* copy the high-order bit */
for (j = 0; j < n; j++) {
Cg--; Cb--; /* for the remaining bits */
*Cg= *(Cb+1)^*Cb; /* do the appropriate XOR */
}
}

Автор:  VSU [ Вто Окт 24, 2006 9:02 pm ]
Заглавие: 

unsigned int graydecode(unsigned int gray)
{
unsigned int bin;
for (bin = 0; gray; gray >>= 1)
{
bin ^= gray;
}
return bin;
}

Автор:  HCL [ Сря Окт 25, 2006 1:50 am ]
Заглавие: 

Ако използваш метода, който е показал [zaphod] и имаш достатьчно гейтове под рька, преобразувай до някаква структура с по-малко нива, че 12 XOR-а навьрзани по този начин, няма да са никак бьрзи.

Автор:  Syrius-B [ Сря Окт 25, 2006 11:29 am ]
Заглавие: 

Нищо по-просто от това преобразуване.
Ако забравите Бейсици, С-та и пр, с няколлко инструкции на асемблер се прави прост цикъл
Старшия бит от входа е = на старшия от идхода.
Всеки следващ изходен бит = EOR с предния и входния, и така до последния
Преобразуването е двустранно Грей към BCD и обратно BCD към Грей с една и съща операция

Автор:  the_real_maniac [ Сря Окт 25, 2006 11:37 am ]
Заглавие: 

EOR == exclusive OR ?
true => XOR
false => 8O

Винаги досега където се говори за exclusive OR съм го виждал XOR, затова и питанката ;-) :-)

Автор:  Syrius-B [ Сря Окт 25, 2006 12:42 pm ]
Заглавие: 

Казва се още "полу-сума", или сума по модул 2
1 * 1 = 0
1 * 0 = 1
0 * 1 = 1
0 * 0 = 0

Автор:  VSU [ Сря Окт 25, 2006 12:54 pm ]
Заглавие: 

тъй де полу сума не полу умножение
1 + 1 = 0 <=== е те заради това :D
1 + 0 = 1
0 + 1 = 1
0 + 0 = 0

Автор:  Syrius-B [ Сря Окт 25, 2006 12:59 pm ]
Заглавие: 

Е, не ми се рисуваше знак + в кръгче - на клавиатурата го нямам :D

Автор:  VSU [ Сря Окт 25, 2006 1:21 pm ]
Заглавие: 

еее майтап де :)

Автор:  MYXATA [ Сря Окт 25, 2006 1:25 pm ]
Заглавие:  ако си вземеш едно ефтино CPLD.....

--======================================================================================================--
library IEEE;

use IEEE.std_logic_1164.all;



entity gray_TO_bin is

port (
-------- clk:in std_logic;--CLOCK ako imash nuvda otkomentirai
a_in: in STD_LOGIC; --MSB input

b_in: in STD_LOGIC;

c_in: in STD_LOGIC;

d_in: in STD_LOGIC; --LSB input in Gray code

a_out: out STD_LOGIC;--MSB output

b_out: out STD_LOGIC;

c_out: out STD_LOGIC;

d_out: out STD_LOGIC --LSB output in binary

);

end gray_TO_bin;


architecture gray_TO_bin_arch of gray_TO_bin is

begin

--if clk'event and clk = '1' then --CLOCK ako imash nuvda otkomentirai
a_out <= a_in;
b_out <= a_in xor b_in;
c_out <= a_in xor b_in xor c_in;
d_out <= a_in xor b_in xor c_in xor d_in;

--end if;--CLOCK ako imash nuvda otkomentirai


end gray_TO_bin_arch;

--===========================================================================--


И така нататък ако искаш си го разшири до какъвто разряд искаш

Автор:  MYXATA [ Сря Окт 25, 2006 1:28 pm ]
Заглавие: 

между впрочем като гледам zaphod го е нарисувал вече....мойто е на VHDL

Автор:  sthx [ Сря Окт 25, 2006 1:41 pm ]
Заглавие:  Re: ако си вземеш едно ефтино CPLD.....

Благодаря на всички за съветите. Даже се престарахте. Зная какво е код на Грей; нямам проблеми с реализацията на схемичката на асемблер , която пусна zaphod. Май същата схема я имаше и в един стар пост, но съм забравил.
Проблемът е , че кодът е непълен, а вероятно има и объркани битове. В момента съм взел старата платка, която прави дешифрацията и съм я дал да я рзнищат. Исках да спестя тази работа, но няма начин.

Автор:  HCL [ Сря Окт 25, 2006 3:01 pm ]
Заглавие: 

Направо разбуди духовете с това "бьрзо да го прехвьрля". Рекох си аз, човекьт има на разположение 10-15ns, какво го занимавате сьс С и Асемблер, да му препорьчам да си синтезира някое GAL-че :)

Страница 1 от 2 Часовете са според зоната UTC + 2 часа [ DST ]
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/