1
votes

I have problem with this code in testbench because it gives me X for cout, and I couldn't find the problem.

Three bit counter Verilog with enable:

`timescale 1ns/1ns
module three_bit_counter(output cout,input en,clk);
    reg [2:0] w;
    always@(negedge clk)begin
        if (en) 
            w <= w + 1;
    end
    assign cout= w & en;
endmodule

And this is my testbench:

`timescale 1ns/1ns
module three_bit_counterTB();
reg en;
reg clk=1;
wire cout;
three_bit_counter tbc(cout,en,clk);
always #20 clk=~clk;
initial begin
    #20 en=1;
    #100;
    $stop;
end
endmodule
1

1 Answers

2
votes

cout is unknown (X) because w is unknown. w is declared as a reg which initializes to X at time 0. Even when en=1, w <= w + 1 still remains X.

You need to initialize w. For simulation purposes, this can be done with:

reg [2:0] w = 0;

A common design approach is to use a reset signal to initialize your registers. You would add a reset input to your design module, then drive it from the testbench. For example:

module three_bit_counter (output cout, input en, clk, reset);
    reg [2:0] w;
    always @(negedge clk or posedge reset) begin
        if (reset)   w <= 0;
        else if (en) w <= w + 1;
    end
    assign cout= w & en;
endmodule