veriloghdlmodelsim

Use of $writememh in for loop


Can we use $writememh in a for loop? I am trying to write to a file from different memories alternatively, and I am getting a warning:

Warning: More indices than needed

I have googled, but nothing is written about this warning. Below is the sample code:

reg [7:0] Mem_x[1023:0];
reg [7:0] Mem_y[1023:0];
reg [7:0] Mem_z[1023:0];
reg [31:0] image[1023:0];

initial
begin

#1000
for (l = 0; l < 25; l = l + 1)  
    
    @(posedge Clock)
     begin 
        $writememh("writefile_out.hex",Mem_x[l]);  
        $writememh("writefile_out.hex",Mem_y[l]); 
        $writememh("writefile_out.hex",Mem_z[l]);
        $writememh("writefile_out.hex",image[l][7:0]); 
     end
end

Solution

  • I assume Mem_x, Mem_y, Mem_z and image are declared something like:

    integer Mem_x[0:24];
    integer Mem_y[0:24];
    integer Mem_z[0:24];
    reg [7:0] image[0:24];
    

    In which case you want a file that reads something like:

    {Mem_x[0]}
    {Mem_y[0]}
    {Mem_z[0]}
    {image[0]}
    {Mem_x[1]}
    {Mem_y[1]}
    {Mem_z[1]}
    {image[1]}
    {Mem_x[2]}
    ...
    

    Where each of those in a hex value for the variable indicated.

    If so, you cannot use $writememh to achieve this; because $writememh overwrites the given file, it does NOT append to it. So, with each call, you are erasing the previous contents of "writefile_out.hex". Also, the reason you are getting that error is because Mem_x[l] and the others are not arrays, they are elements of arrays and $writememh expects an array as an argument (thus, too many indexes error).

    However, you can use $fdisplay to achieve what you want (and then some). Heres an example:

    integer outfile;
    integer i;
    reg [7:0] mem1[0:9];
    reg [7:0] mem2[0:9];
    
    initial begin
      outfile = $fopen("out.hex");
      ...
      for (i = 0; i < 10; i = i + 1) begin
        $fdisplay(outfile, "%02x\n%02x\n", mem1[i], mem2[i]);
      end
      ...
    end
    

    Using $fdisplay means you can format the output however you like, so it doesnt have to be constrained to the standard hex format used by $readmemh and $writememh, unless you want it to be, then you just use something like I have above.