Read and write array from txt in Verilog

2019-05-24 09:51发布

问题:

First of all I want to say that I'm running the simulation in ADS (Advanced Design System 2017) through a Verilog model compiled in ModelSim.

My objective is loading data from a .txt file into the testbench as input in order to run the simulation, and afterwards save the results of this simulation in another .txt file.

Here is the content for the input test .txt file called "param.txt":

1
2
3
4
5
6
7
8
9
10

And here is my Verilog testbench code:

`include "disciplines.vams"


module resistor(p,n);
electrical p,n;
parameter real R=50.0;
integer file;
integer out;
real pwm_A[0:50];
integer i;
integer j=1;


analog begin

    @(initial_step) // Initial Conditions
    begin


////////////// Read

file=$fopen("param.txt","r");

    if (file)  $display("File was opened successfully : %0d", file);
    else       $display("File was NOT opened successfully : %0d", file);

    for (i=1; i<50; i=i+1) begin  
        pwm_A[i]=$fscanf(file,"%d",j);
        j = j+1;
    end



////////////// Write


out=$fopen("out.txt","w");

    for (i=1; i<=15; i=i+1) begin  

        $fwrite(out,"%d\n",pwm_A[i]);

    end

// Trying to manually display data
$fdisplay(out,123);


$fclose(file);
$fclose(out);


end

// Simulation (doesnt matter)
V(p,n) <+ R * I(p,n);


end
endmodule

The simulation log has no errors or warnings:

File was opened successfully : -32

But the output .txt file called "out.txt" generates this:

1
1
1
1
1
1
1
1
1
1
0
0
0
0
0
123 

Instead of the original data.

It's noticeable that the '123' manually introduced value has no problems to be written, but the rest of the data are '0' or '1'.

May anyone spot the problem?

Thanks in advance.

回答1:

This line here

pwm_A[i]=$fscanf(file,"%d",j);

should read

$fscanf(file,"%d",pwm_A[i]);

The $fscanf system function is the opposisite of $fdisplay - the function outputs into variables in its argument list. It returns the number of items successfully read from the line. This will (hopefully) be 1 for the first ten lines and will be 0 for the next lines. So, you should really check that number and do something if it's not what you expect, eg:

count = $fscanf(file,"%d",pwm_A[i]);
if (count != 1) 
  // whatever