Spice
Spice

Reputation: 31

How to write verilog testbench to loop through a n bit input n times

I am writing a testbench to loop through a 16 bit Data input I have where it will go through each bit and change the value from a 0 to a 1, for example the first iteration would be 10000...00, second would be 010000...00, 001000...00, and so on. Here is what I have right now.

module testbench();

//inputs
reg [15:0] Data = 0;
//outputs
wire [15:0] Errors;

OLS uut (
    .Data (Data),
    .Errors (Errors)
);


integer k = 0;

initial
begin
    Data = 0;
    for(k = 0; k<16; k=k+1)
    begin
        Data[k] = 1;
        if(k>0)
        begin
            Data[k-1] = 0;
        end
    end
end

endmodule

enter image description here

enter image description here

I am unsure if I have made a mistake with my testbench or if this is expected behavior, but I can't tell how I am supposed to see the expected output in each iteration. I have tried to use console outputs to keep track of where I am in the loop and if I am resetting the previous bit to 0 after I am done with that one.

I expect to get 0 in the 'Errors' output in every iteration, so basically I need help to verify my code does what I want it to do, and also how to read the graphical output of the simulation.

Upvotes: 0

Views: 1395

Answers (1)

Mikef
Mikef

Reputation: 2508

The loop in the post unrolls in 0 time.
Some delay is needed to create a waveform.
Also need a $finish, otherwise the testbench runs forever.

Like this:

module testbench();

//inputs
reg [15:0] Data = 0;

integer k = 0;

  
initial
  begin
    #100;
  end
  
initial
begin
    Data = 0;
    for(k = 0; k<16; k=k+1)
    begin
        Data[k] = 1;
        if(k>0)
        begin
            Data[k-1] = 0;
        end
      #5; // delay here
    end
end
  
initial
  begin
    $dumpfile("dump.vcd"); 
    $dumpvars;
 end

endmodule

enter image description here

Upvotes: 1

Related Questions