Verilog实现代码:
module Counter(clk,en,rst,cnt_value);
input clk;
input rst;
input en;
output [3:0]cnt_value;
reg [3:0]cnt;
always @(posedge clk or negedge rst)
if(!rst)
cnt <= 4'd0;
else if(en)begin
cnt <= cnt+1'b1;
end
assign cnt_value = cnt;
endmodule
Modelsim仿真代码:
`timescale 1ns/1ns
`define clk_period 10
module Counter_tb;
//信号激励
reg clk_t;
reg en_t;
reg rst_t;
wire[3:0]cnt_value_t;
//例化
Counter Counter1(
.clk(clk_t),
.en(en_t),
.rst(rst_t),
.cnt_value(cnt_value_t[3:0]));
//时钟周期100M:10ns 1个周期
initial clk_t = 1;
always #(`clk_period/2) clk_t = ~clk_t;
initial begin
en_t = 0;
rst_t = 1;
#(`clk_period*20);
rst_t = 0;
#(`clk_period*20);
rst_t = 1; //rst复位给初始值
#(`clk_period*20);
en_t = 1;
#(`clk_period*200); //en有效一段时间
en_t = 0;
#(`clk_period*50);
rst_t = 0;
#(`clk_period*50);
rst_t = 1;
$stop;
end
endmodule
仿真结果: