GrayCode for state machine

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于GrayCode for state machine的主要内容,如果未能解决你的问题,请参考以下文章

激活用户时带有acts_as_state_machine的restful_authentication中的DoubleRenderError

Moore and Mealy machines,Harel statecharts,UML state machines

Replicated State Machine和WAL

Finite State Machine 是什么?

Mina State machine状态机讲解

证明与计算: 有限状态机(Finite State Machine)