GrayCode for state machine

How & Why use Gray Code

A gray counter is a binary counter where only one bit changes at a time.

Gray code is mostly used to send values across clock domains (this way it has an uncertainty of only 1).

The easiest way 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 < 16; 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

posted @ 2016-02-05 11:17  pengdada  阅读(206)  评论(0编辑  收藏  举报