verilog 有限狀態機的小小實例演示及仿真——序列檢測器


在數字電路中,FSM(有限狀態機)的使用還是比較普遍的,下面舉一個序列檢測器。

verilog(Detector110.v)代碼如下:

 

/*
finite state machine----FSM
implemente file
有限狀態機的實例
2012/05/22
Iverilog + GTKWave in windows XP sp3
*/

`timescale 1ns/100ps

module Detector110(input a, clk, reset, output w);
    parameter [1:0] s0 = 2'b00,
                    s1 = 2'b01,
                    s2 = 2'b10,
                    s3 = 2'b11;
    reg [1:0] current;
    
    always @ (posedge clk)
        begin
            if(reset)
                current = s0;
            else
                case (current)
                s0:    if(a) current <= s1;
                    else current <= s0;
                s1: if(a) current <= s2;
                    else current <= s0;
                s2: if(a) current <= s2;
                    else current <= s3;
                s3: if(a) current <= s1;
                    else current <= s0;
            endcase
        end
        
        assign w = (current == s3) ? 1 : 0;
endmodule

再寫一個testbench文件test_tb.v:

/*
finite state machine----FSM
testbench file for Detector110.v
有限狀態機的實例
2012/05/22
Iverilog + GTKWave in windows XP sp3
*/

`timescale 1ns/100ps

module test;
    reg aa, clk, rst;
    wire ww;
    Detector110 UUT(aa, clk, rst, ww);
    
    initial
        begin
            aa = 0;
            clk = 0;
            rst = 1;
        end
    
    initial
        repeat (44) #7 clk = ~clk;
    
    initial
        repeat (15) #23 aa = ~aa;
    
    initial
        begin
            #31 rst = 1;
            #23 rst = 0;
        end
    
    always @ (ww)
        if(ww == 1)
            $display("A 1 was detector on w at time = %t,",$time);
            
    initial
        begin            
            $dumpfile("test.vcd");
            $dumpvars;
        end
endmodule

寫一個批處理文件go.bat:

ECHO OFF
ECHO *********************************
ECHO *        Batch file
ECHO *********************************
ECHO *
ECHO ON
iverilog -o test Detector110.v test_tb.v
vvp -n test -lxt2
cp test.vcd test.lxt
gtkwave test.lxt

 執行之后:

E:\lm\verilog\iverilog\MooreState>go.bat

E:\lm\verilog\iverilog\MooreState>ECHO OFF
*********************************
*        Batch file
*********************************
*

E:\lm\verilog\iverilog\MooreState>iverilog -o test Detector110.v test_tb.v

E:\lm\verilog\iverilog\MooreState>vvp -n test -lxt2
LXT2 info: dumpfile test.vcd opened for output.
A 1 was detector on w at time =                 1050,
A 1 was detector on w at time =                 1470,
A 1 was detector on w at time =                 1890,
A 1 was detector on w at time =                 2870,

E:\lm\verilog\iverilog\MooreState>cp test.vcd test.lxt

E:\lm\verilog\iverilog\MooreState>gtkwave test.lxt

之后啟動了GTKWave,截圖如下:

 哈哈!不錯誒!

這里解釋一下testbench里的

`timescale 1ns/100ps

這里表明仿真的時間單位為ns,而仿真的時間精度為100ps,即0.1ns,這意味着可以在程序中使用小數的時間值為0.1ns。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM