module count_module( input clk, input rst_n, input mode, output reg [3:0]number, output reg zero ); reg [3:0]out; always @ (posedge clk or negedge rst_n) begin if(!rst_n) begin number<=4'd0; out<=4'd0; end else begin if(mode) begin out<= out==4'd9 ? 4'd0 : out+4'd1; end else begin out<= out==4'd0 ? 4'd9 : out-4'd1; end number<=out; end end always@(posedge clk or negedge rst_n) begin if(!rst_n) begin zero<=1'b0; end else begin zero<= out==0 ? 1'b1 : 1'b0; end end endmodule
`timescale 1ns/1ns module testbench(); reg rst,mode; reg clk=1; wire [3:0]number; wire zero; count_module u1( . clk(clk), .mode(mode), .rst_n(rst), .number(number), .zero(zero) ); always #5 clk = ~clk; // Create clock with period=10 initial begin rst=0; #10 rst=1;mode=1; #150 mode=0; #200 ; $finish; end endmodule
仿真波形图如下: