1. 程式人生 > >格雷碼(Gray code)仿真

格雷碼(Gray code)仿真

HA 實現 鏈接 計數 variable hide 記錄 strong pan

作者:桂。

時間:2018-05-12 16:25:02

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


前言

FIFO中的計數用的是格雷碼,簡要記錄格雷碼的分析思路。

一、格雷碼與8421碼對應關系

技術分享圖片

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

技術分享圖片

即格雷碼是:8421碼從最右邊起,依次與左邊一位異或,最左邊一位不變,對應實現語言:

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

二、仿真實現

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{1b 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 + 4b1;
    end
end
//main
GrayCounter gray_inst(
.Enable_in(en), 
.Clear_in(clr), 
.Clk(clk), 
.GrayCount_out(GrayCount_out)
);

endmodule
View Code

技術分享圖片

電路圖看出:

技術分享圖片

主要是LUT、D觸發器、DS觸發器,原語實現也較為方便。

格雷碼(Gray code)仿真