verilogvlsi

Testbench for writing to the file in Verilog


This is my Testbench for a design and I am applying inputs to the design using the function '$readmemb'. I have opened a file using '$fopen' and wish to write the result 'out' in the file named 'jaja.txt' but I am unable to do so.

Sometimes the file 'jaja.txt' shows nothing and sometimes don't care 'x'.

module trimmed_tb();
reg clk,rst; // clock  and reset
reg [7:0]P;
wire [7:0]out;
reg [12:0] vectornum; // bookkeeping variables
reg [7:0] testvectors[4096:1]; //array of testvectors

integer outfile;
   
//instantiate device under test
median_fil_final dut(.clk(clk),.rst(rst),.P(P),.out(out));

// generate clock
always #5 clk=~clk;

// at start of test, load vectors
initial 
begin
$readmemb("C:/Users/OneDrive/Desktop/Noisy_pixels.mem",testvectors); // Read vectors 

outfile = $fopen("C:/Users/OneDrive/Desktop/jaja.txt","w");

vectornum = 0;
rst=0; 
end

// apply test vectors on rising edge of clk
always @(posedge clk)
begin
 P = testvectors[vectornum];
end


// increment index on falling edge of clk
always @(negedge clk)begin
if(~rst)begin
vectornum = vectornum + 1; // read next vector
if (testvectors[vectornum] === 8'bx)
begin
$display("tests completed");
$finish;// End simulation
end
end
end

initial begin
  $fclose(outfile);
end

endmodule

I tried writing to the file by putting the '$fdisplay' in the negedge clk block and then with the '$fclose'.

I am expecting to get my 'out' result to be written in the 'jaja.txt' file.


Solution

  • The first thing you do at t=0 in this process is to close outfile

    initial begin
      $fclose(outfile);
    end
    

    The testbench will not be able to write anything to outfile at any edge of the clock because you closed the outfile at t=0.

    Looking closer, there is actually a race at t=0 because you open it in another process at t=0. Its logically ambiguous if it will get opened or closed first. I would resolve this by opening and cloning in the same process (begin-end block).

    Close the outfile when the testbench is done, maybe just before $finish.

    The testbench has other problems but this one is directly stopping the writes, in an ambigious way; the outcome of the race can vary. Either in never gets opened or never closed.


    Another issue
    Your clock generator is not generating any clocks

    // generate clock
    always #5 clk=~clk;
    

    Variable clk is never initialized, it starts as x, and not x is x.
    One solution is to use this construct

    initial begin
      clk = 0;
      forever 
        #5 clk = ~clk;
    end