Pages

Sunday, November 5, 2017

File Reading and Writing in Verilog - Part 1

File reading and writing is a very useful thing to know in Verilog. The possibility to read test input values from files, and write output values for later verification makes testbench codes easy to write and understand.

There are few ways to read or write files in Verilog. So I will explain the whole thing in few different posts. In this first part we will learn the following things,

  • How to read hexadecimal values from a file using readmemh function.
  • How to read binary values from a file using readmemb function.
  • How to write a file with binary values using fopen and fdisplay.
  • How to write a file with decimal values using fopen and fdisplay.
  • How to write a file with hexadecimal values using fopen and fdisplay.

Verilog code for File Read and Write:

`timescale 1ns / 1ps

module tb();

    reg [7:0] A [0:15]; //memory declaration for storing the contents of file.
    integer outfile1,outfile2,outfile3; //file descriptors
    integer i;  //index used in "for" loop

initial begin
    //read the contents of the file A_hex.txt as hexadecimal values into memory "A".
    $readmemh("A_hex.txt",A);
    //The $fopen function opens a file and returns a multi-channel descriptor 
    //in the format of an unsized integer. 
    outfile1=$fopen("A_write_dec.txt","w");
    outfile2=$fopen("A_write_bin.txt","w");
    outfile3=$fopen("A_write_hex.txt","w");
    
    //Write one by one the contents of vector "A" into text files.
    for (= 0; i < 16; i = i +1) begin
        $fdisplay(outfile1,"%d",A[i]);  //write as decimal
        $fdisplay(outfile2,"%b",A[i]);  //write as binary
        $fdisplay(outfile3,"%h",A[i]);  //write as hexadecimal
    end 
    //once writing is finished, close all the files.
    $fclose(outfile1);
    $fclose(outfile2);
    $fclose(outfile3);
    //wait and then stop the simulation.
    #100;
    $stop;
end 

Now if you want to read a binary file instead of hex file you just have to replace a single line in the above code,

Replace the line $readmemh("A_hex.txt",A);
with $readmemb("A_bin.txt",A);

 That's all! The output files should look the same in both the cases.

A screenshot of input files and output files are given below:


The input files can be downloaded from here,

The code was tested using Xilinx ISE 14.6 tool.

1 comment: