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。

posted @ 2012-05-22 21:11  wdliming  阅读(7121)  评论(0编辑  收藏  举报