格雷码(Gray code),又叫循环二进制码或反射二进制码 在数字系统中只能识别0和1,各种数据要转换为二进制代码才能进行处理,格雷码是一种无权码,采用绝对编码方式,典型格雷码是一种具有反射特性和循环特性的单步自补码,它的循环、单步特性消除了随机取数时出现重大误差的可能,它的反射、自补特性使得求反非常方便。格雷码属于可靠性编码,是一种错误最小化的编码方式。
因为,自然二进制码可以直接由数/模转换器转换成模拟信号,但某些情况,例如从十进制的3转换到4时二进制码的每一位都要变,使数字电路产生很大的尖峰电流脉冲。而格雷码则没有这一缺点,它是一种数字排序系统,其中的所有相邻整数在它们的数字表示中只有一个数字不同。它在任意两个相邻的数之间转换时,只有一个数位发生变化。它大大地减少了由一个状态到下一个状态时逻辑的混淆。另外由于最大数与最小数之间也仅一个数不同,故通常又叫格雷反射码或循环码。
下表为几种自然二进制码与格雷码的对照表:
十进制数 | 自然二进制数 | 格雷码 |
0 | 0000 | 0000 |
1 | 0001 | 0001 |
2 | 0010 | 0011 |
3 | 0011 | 0010 |
4 | 0100 | 0110 |
5 | 0101 | 0111 |
6 | 0110 | 0101 |
7 | 0111 | 0100 |
8 | 1000 | 1100 |
9 | 1001 | 1101 |
10 | 1010 | 1111 |
11 | 1011 | 1110 |
12 | 1100 | 1010 |
13 | 1101 | 1011 |
14 | 1110 | 1001 |
15 | 1111 | 1000 |
一般的,普通二进制码与格雷码可以按以下方法互相转换:
二进制码->格雷码(编码):从最右边一位起,依次将每一位与左边一位异或(XOR),作为对应格雷码该位的值,最左边一位不变(相当于左边是0);
格雷码-〉二进制码(解码):从左边第二位起,将每位与左边一位解码后的值异或,作为该位解码后的值(最左边一位依然不变)。
View Code
1 // Gray counter 2 3 module gray_count 4 ( 5 input clk, enable, reset, 6 output reg [7:0] gray_count 7 ); 8 9 // Implementation: 10 11 // There's an imaginary bit in the counter, at q[-1], that resets to 1 12 // (unlike the rest of the bits of the counter) and flips every clock cycle. 13 // The decision of whether to flip any non-imaginary bit in the counter 14 // depends solely on the bits below it, down to the imaginary bit. It flips 15 // only if all these bits, taken together, match the pattern 10* (a one 16 // followed by any number of zeros). 17 18 // Almost every non-imaginary bit has a submodule instance that sets the 19 // bit based on the values of the lower-order bits, as described above. 20 // The rules have to differ slightly for the most significant bit or else 21 // the counter would saturate at it's highest value, 1000...0. 22 23 // q is the counter, plus the imaginary bit 24 reg q [7:-1]; 25 26 // no_ones_below[x] = 1 iff there are no 1's in q below q[x] 27 reg no_ones_below [7:-1]; 28 29 // q_msb is a modification to make the msb logic work 30 reg q_msb; 31 32 integer i, j, k; 33 34 always @ (posedge reset or posedge clk) 35 begin 36 if (reset) 37 begin 38 39 // Resetting involves setting the imaginary bit to 1 40 q[-1] <= 1; 41 for (i = 0; i <= 7; i = i + 1) 42 q[i] <= 0; 43 44 end 45 else if (enable) 46 begin 47 // Toggle the imaginary bit 48 q[-1] <= ~q[-1]; 49 50 for (i = 0; i < 7; i = i + 1) 51 begin 52 53 // Flip q[i] if lower bits are a 1 followed by all 0's 54 q[i] <= q[i] ^ (q[i-1] & no_ones_below[i-1]); 55 56 end 57 58 q[7] <= q[7] ^ (q_msb & no_ones_below[6]); 59 end 60 end 61 62 63 always @(*) 64 begin 65 66 // There are never any 1's beneath the lowest bit 67 no_ones_below[-1] <= 1; 68 69 for (j = 0; j < 7; j = j + 1) 70 no_ones_below[j] <= no_ones_below[j-1] & ~q[j-1]; 71 72 q_msb <= q[7] | q[6]; 73 74 // Copy over everything but the imaginary bit 75 for (k = 0; k < 8; k = k + 1) 76 gray_count[k] <= q[k]; 77 end 78 79 endmodule