计数器
verilog
实现0-100计数
module counter(
input clk,
input rst_n,
output reg [7:0] cnt
);
always @ (posedge clk,negedge rst_n)
begin
if(rst_n == 1'b0)
cnt <= 8'd0;
else if(cnt == 8'd100)
cnt <= 8'd0;
else
cnt <= cnt + 1'b1;
end
endmodule
tb
module counter_tb;
// Inputs
reg clk;
reg rst_n;
// Outputs
wire [7:0] cnt;
// Instantiate the Unit Under Test (UUT)
counter uut (
.clk(clk),
.rst_n(rst_n),
.cnt(cnt)
);
initial begin
// Initialize Inputs
clk = 0;
rst_n = 0;
// Wait 100 ns for global reset to finish
#100;
rst_n = 1;
#10000;
$stop;
// Add stimulus here
end
always #10 clk = ~clk;
endmodule
仿真波形
实现一毫秒的计时
module time_counter(
input clk,
input rst_n,
output reg flag
);
parameter t = 50_000;
reg [15:0] cnt;
always @ (posedge clk,negedge rst_n)
begin
if(rst_n == 1'b0)
cnt <= 16'd0;
else if (cnt == t-1)
cnt <= 16'd0;
else
cnt <= cnt + 1'b1;
end
always @ (posedge clk,negedge rst_n)
begin
if(rst_n == 1'b0)
flag <= 1'b0;
else if (cnt == t-1)
flag <= 1'b1;
else
flag <= 1'b0;
end
endmodule
tb
module time_counter_tb;
// Inputs
reg clk;
reg rst_n;
// Outputs
wire flag;
// Instantiate the Unit Under Test (UUT)
time_counter time_counter_inst(
.clk(clk),
.rst_n(rst_n),
.flag(flag)
);
initial begin
// Initialize Inputs
clk = 0;
rst_n = 0;
// Wait 100 ns for global reset to finish
#100;
// Add stimulus here
rst_n = 1;
#10000;
$stop;
end
always #10 clk = ~clk;
endmodule
手动继续波形