1.首先写一个简单的加法器。
module counter_ud (clk,rstn,load,load_en,count);
input clk;
input rstn; //复位端
input load_en; //使能端
input [3:0] load;
output [3:0] count;
logic [3:0] load;
logic[3:0] count;
always @ (posedge clk or negedge rstn) begin
if (!rstn)
count <= 0;
else begin
if (load_en)
count <= load;
else
count <= count + 1;
end
end
endmodule
2.interface模块。
interface cnt_if (input clk);
logic rstn;
logic load_en;
logic [3:0] load;
logic [3:0] count;
endinterface
3.testbench模块。
module tb;
logic clk;
always #5 clk = ~clk; //产生周期为10的clk
cnt_if cnt_if0 (clk); //实例化interface
//将接口一一对应
counter_ud u0 ( .clk (cnt_if0.clk),
.rstn (cnt_if0.rstn),
.load_en (cnt_if0.load_en),
.load (cnt_if0.load),
.count (cnt_if0.count));
initial begin
//监测数据的变化
$monitor("[%0t] load_en = %0d;load = %0d; count = %0d",$time,cnt_if0.load_en,cnt_if0.load,cnt_if0.count);
//初始化变量
clk <= 0;
cnt_if0.rstn <= 0;
cnt_if0.load_en <= 1;
cnt_if0.load <= 0;
//5个周期之后开始仿真
repeat (5) @(posedge clk);
cnt_if0.rstn <= 1;
#(10); cnt_if0.load_en <=1;cnt_if0.load<=6;
#(10); cnt_if0.load_en <=1;cnt_if0.load<=8;
#(10); cnt_if0.load_en <=1;cnt_if0.load<=10;
#(10); cnt_if0.load_en <=0;cnt_if0.load<=10;
#(10); cnt_if0.load_en <=0;cnt_if0.load<=10;
//重复两个周期后结束
repeat (2) @(posedge clk);
$finish;
end
endmodule
4.SimLog
当使能端load_en = 1时,count = load;
当使能端load_en = 0时,count = count +1;
因为非阻塞赋值,count的变化总是落后一个周期。