How & Why Use Gray Code
A gray counter is a binary counter where the one bit changes at a time.
Gray code is mostly used to send values across clock domains (the this-to-the-it has a uncertainty of only 1).
The easiest-to-create a gray counter is to first make a binary counter, and then convert the value to gray.
=======================================================================
VS2013, Simulation
-------------------------------------------
#include <stdio.h>
#include <string>
Template<int bits>
std::string GetBits (unsigned int val) {
std::string str;
for (int i = BITS-1; I >= 0; I-) {
char c = ' 0 ';
if (Val & (1 << i) c = ' 1 ';
Str.push_back (c);
}
return str;
}
Template<int bits>
unsigned int getgraycode () {
unsigned long mask = (1<<bits)-1;
static unsigned int next = 0;
unsigned int nrtn = 0;
Nrtn = (Next >> 1) ^ (next);
next++;
if (Next > Mask) next = 0;
return NRTN;
}
void Testgraycode () {
//generate 4Bit Gray Code
const int BITS = 4;
printf ("%6s:%s \ n", "Index", "Graycode");
printf ("---------------------------------\ n");
for (int i = 0; i <; i++) {
std::string str = getbits<bits> (getgraycode<bits> ());
printf ("%06d:%s \ n", I, Str.c_str ());
}
printf ("---------------------------------\ n");
}
void Main () {
Testgraycode ();
}
----------------------------------------------------
4Bit Graycode Result:
/////////////////////////////////////////////////////////////////////////////////////
-------------------------------Verilog-----------------------------------
module Generategraycode (CLK, Rst_n, gray_code);
parameter bits_count = 4;
input CLK, rst_n;
output [bits_count-1:0] Gray_code;
reg [bits_count-1:0]cnt = 1 ' b0;
Always @ (Posedge CLK or Negedge rst_n)
begin
if (! rst_n) CNT <= 0;
Else
begin
CNT <= cnt + 1 ' B1;
End
End
Assign Gray_code = (CNT >> 1 ' B1) ^ cnt;
Endmodule
Graycode for state machine