格雷码(Gray code)仿真

作者:桂。

时间:2018-05-12  16:25:02

链接:http://www.cnblogs.com/xingshansi/p/9029081.html 


前言

FIFO中的计数用的是格雷码,简要记录格雷码的分析思路。

一、格雷码与8421码对应关系

格雷码(Gray code)仿真

通过真值表分析,可以得出:

格雷码(Gray code)仿真

即格雷码是:8421码从最右边起,依次与左边一位异或,最左边一位不变,对应实现语言:

GrayCount_out <= {BinaryCount[COUNTER_WIDTH-1],BinaryCount[COUNTER_WIDTH-2:0] ^ BinaryCount[COUNTER_WIDTH-1:1]};

另外:

格雷码(Gray code)仿真

二、仿真实现

Graycounter.v:

`timescale 1ns/1ps

module GrayCounter(Enable_in, Clear_in, Clk, GrayCount_out);
parameter   COUNTER_WIDTH = 4;

output reg  [COUNTER_WIDTH-1:0]    GrayCount_out;  //'Gray' code count output.
    
input wire  Enable_in;  //Count enable.
input wire  Clear_in;   //Count reset.    
input wire  Clk;

/////////Internal connections & variables///////
reg    [COUNTER_WIDTH-1:0]         BinaryCount;

/////////Code///////////////////////

always @ (posedge Clk)
begin
    if (Clear_in) begin
        BinaryCount   <= {COUNTER_WIDTH{1'b 0}} + 1;  //Gray count begins @ '1' with
        GrayCount_out <= {COUNTER_WIDTH{1'b 0}};      // first 'Enable_in'.
    end
    else if (Enable_in) begin
        BinaryCount   <= BinaryCount + 1;
        GrayCount_out <= {BinaryCount[COUNTER_WIDTH-1],
                          BinaryCount[COUNTER_WIDTH-2:0] ^ BinaryCount[COUNTER_WIDTH-1:1]};
    end
end

endmodule

testbench:

`timescale 1ns / 1ps
module graycounter_tb;
parameter   COUNTER_WIDTH = 4;

logic clk,rst;
logic clr,en;
logic [COUNTER_WIDTH-1:0]    GrayCount_out;
initial 
begin
clk = 0;
rst = 1;
#20
rst = 0;
clr <= 1;
en <= 0;
#100
clr <= 0;
en <= 1;
#2000
$stop;
end

logic [3:0] counter;

always #2 clk = ~clk;

always @(posedge clk)
begin
    if(rst | clr)
    begin
        counter <= 0;
        clr <= 1;
        en <= 0;
    end
    else
    begin
        counter <= counter + 4'b1;
    end
end
//main
GrayCounter gray_inst(
.Enable_in(en), 
.Clear_in(clr), 
.Clk(clk), 
.GrayCount_out(GrayCount_out)
);

endmodule
View Code

格雷码(Gray code)仿真

电路图看出:

格雷码(Gray code)仿真

主要是LUT、D触发器、DS触发器,原语实现也较为方便。