Read Binary Data From .txt to Array in Verilog
Reading files from Verilog models
Introduction
This guide describes how you lot can read files in a Verilog model using a set up of system functions which are based on the C stdio package. With these arrangement functions you can perform file input directly in Verilog models without having to larn C or the PLI. Download read.tar.gz, the Unix version of the code, plus documentation and examples. This works with VCS and Verilog-Xl simply not NC-Verilog.- Copyright
- Overview
- File Input Functions
- Restrictions and Caveats
- Reading design files
- Comparing outputs with expected results
- Reading script files
- Reading data files into memories
- Linking with VCS
- Linking with Verilog-Xl
[Upwards]
Copyright
All code and this user guide are copyright (C) 1995 -1997 past Christian B. Spear, spear@viewlogic.com, (508) 303-5252 If you have any updates, bug fixes, or enhancements, or want the latest version, please contact me.This plan is free software; you tin redistribute it and/or modify it under the terms of the GNU General Public License every bit published by the Free Software Foundation; either version 2 of the License, or (at your option) whatever afterward version.
This program is distributed in the hope that it volition be useful, only WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A Detail PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License forth with this program; if non, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
Overview
This application note describes how your Verilog model or testbench can read text and binary Unix files to load memories, employ stimulus, and control simulation. The format of the file-read functions is based on the C stdio routines, such as fopen, fgetc, and fscan.The Verilog language has a rich set of system functions to write files ($fdisplay, $fwrite, etc.) but but reads files with a single, fixed format ($readmem). In the past if you wanted to read a file that was not in $readmem format, you lot would have to learn the Programming Language Interface (PLI) and the C language, write C code to read the file and laissez passer values into Verilog, then debug the combined C and Verilog lawmaking.
Still, using the new file-read system functions yous can perform your file I/O directly from Verilog. You lot tin write Verilog HDL to:
- read stimulus files to apply patterns to the inputs of a model
- read a file of expected values for comparison with your model
- read a script of commands to drive a simulation
- read either ASCII or binary files into Verilog regs and memories
Note that these system tasks comport the aforementioned as the equivalent stdio routines. For example, $fscanf will skip over white-space, including blank lines, just like fscanf(). You can prototype code in C then convert information technology to Verilog.
File Input Functions
The file-read system functions and tasks are based on the C stdio routines. For more than information on the stdio routines, consult a C manual. The major differences between these system tasks and C are caused by the lack of a pointer variable in the Verilog language. Strings in Verilog are stored in registers, with viii bits needed to store a unmarried grapheme.OPEN A FILE
integer file; file = $fopenr("filename"); The function $fopenr opens a file for reading. The file name tin can be either a quoted cord or a reg property the file name. If the file was successfully opened, it returns an integer containing the file number (1..MAX_FILES) or EOF (-ane) if in that location was an error. Notation that this is not the same role as $fopen which opens a file for writing. Shut A FILE
integer file, r; r = $fcloser(file);The function $fcloser closes a file for input. It returns EOF if there was an error, otherwise 0. Notation that this is not the same task equally $fclose which closes files for writing.
TEST FOR Cease OF FILE
integer file; reg eof; eof = $feof(file);The function $feof tests for end of file. If an terminate-of-file has been reached while reading from the file, a non-zero value is returned; otherwise, a 0 is returned.
READ A SINGLE CHARACTER
integer file, char; char = $fgetc(file);The office $fgetc reads a unmarried character from the specified file and returns it. If the end-of-file is reached, $fgetc returns EOF. Y'all should utilise a 32-chip register to hold the result from $fgetc to tell the difference between the character with the value 255 and EOF.
PUSH BACK A Graphic symbol
integer file; reg [7:0] char, r; r = $ungetc(char, file);The role $ungetc pushes the character back into the file stream. That grapheme will be the next read by $fgetc. It returns the character if it was successfully pushed back or EOF if it fails.
READ A STRING
integer file, n, r; reg [n*8-1:0] cord; r = $fgets(string, northward, file);The function $fgets reads a string from the file. Characters are read from the file into cord until a newline is seen, stop-of-file is reached, or due north-i characters have been read. If the end-of-file is encountered, $fgets returns a 0 and string is unchanged; otherwise, $fgets returns a 1.
READ FORMATTED TEXT
integer file, count; count = $fscanf(file, format, args); count = $sscanf(string, format, args);The function $fscanf parses formatted text from the file according to the format and writes the results to args . $sscanf parses formatted text from a cord. See a C reference manual for detailed data on fscanf, plus examples later in this note.
The format can be either a string constant or a reg. It can contain:
- Whitespace characters such every bit space, tab (\t), or newline (\n). One or more than whitespace characters are treated every bit a single grapheme, and tin can match zippo or more than whitespace characters from the input.
- Conversion specifications which start with a %. Next is an optional *, which suppresses assignment. Then is an optional field width in decimal. Lastly is the operator grapheme every bit follows:
- b -- Binary values 0, ane, X, x, Z, z, _
- d -- Decimal values 0-nine, _, no X, x, Z, or z
- o -- Octal values 0-seven, _, X, x, Z, z
- h or ten -- Hexadecimal values, 0-9, A-F, a-f, _, X, 10, Z, z
- c -- A single grapheme
- f -- A floating betoken number, no _, X, x, Z, or z
- s -- A string
- % -- The per centum character
- Other characters which must lucifer the characters read from the file. Special characters are \" for the " character, \\ for the \ character, \oNNN is a single character whose ASCII value is specified by the octal number NNN, and %% for the character %.
Annotation: $sscanf does non let %f
$fscanf and $sscanf return the number of successful assignments performed.
FIND THE FILE POSITION
integer file, position; position = $ftell(file);The office $ftell returns the position in the file for utilise by $fseek. If at that place is an mistake, it returns a -i.
POSITION A FILE
`ascertain SEEK_SET 0 `ascertain SEEK_CUR 1 `define SEEK_END two integer file, offset, position, r; r = $fseek(file, 0, `SEEK_SET); /* Beginning */ r = $fseek(file, 0, `SEEK_CUR); /* No issue */ r = $fseek(file, 0, `SEEK_END); /* End of file */ r = $fseek(file, position, `SEEK_SET); /* Previous loc */The function $fseek allows random admission in a file. You tin position at the kickoff or end of a file, or employ the position returned from $ftell.
READ BINARY DATA
integer r, file, start, count; reg [xv:0] mem[0:10], r16; r = $fread(file, mem[0], start, count); r = $fread(file, r16);The function $fread reads a binary file into a Verilog memory. The start argument is either a register or a retentiveness name, which must have a subscript, though the value of the subscript is ignored. start and count are optional.
By default $fread volition store information in the kickoff information location through the final location. For the memory upwards[10:20], the first location loaded would be up[x], so upward[11]. For down[twenty:10], the first location would be downwards[x], and then downwardly[11].
start and count are ignored if $fread storing data in a reg instead of a retentivity. No warning is printed if the file contains more information than will fit in the retention.
start is the word showtime from the lowest element in the retentivity. For first = 2 and the memory up[10:20], the kickoff data would be loaded at upwardly[12]. For the retention down[20:ten] , the commencement location loaded would be down[12], and then downward[13].
$fread returns the number of elements read from the file, If $fread terminates early on because of an error, information technology will return the number of elements successfully read. $feof can exist used to determine whether the end-of-file was reached during $fread.
The information in the file is broken into bytes according to the width of the retentiveness. An viii-bit broad memory takes one byte per location, while a 9-bit wide retention takes 2 bytes. Care should be taken when using memories with widths not evenly divisible by viii as there may exist gaps in the information in the memory vs. data in the file.
Restrictions and Caveats
Y'all should exist aware of following restrictions in using these Verilog functions vs. the stdio functions in C, which are imposed past the Verilog linguistic communication :- Because these are Verilog arrangement functions, you must always apply the return value equally in:
- Verilog does non allow assignments inside a provisional. Thus the C lawmaking fragment:
while (c=fgetc(stream) != EOF) { <process input> } turns into the Verilog code: c = $fgetc(file); while (c !== `EOF) brainstorm <process input> c = $fgetc(file); end
- $fgets only returns a single bit, 0 = error, 1 = no fault , dissimilar fgets in C, which returns a string pointer.
- $fread is very dissimilar from fread in C. The order of arguments is different, and the arguments are oriented towards writing to a Verilog retentivity instead of a C character cord. Meet folio five for more than info.
- $fscanf can not exist used to read binary files, or any files with null characters. Considering of the cord processing that $fscanf uses, a nil in the middle of an ASCII field volition prematurely finish the field.
The maximum number of files (MAX_FILES) is set in the C code to 12. The maximum string size is 1000 characters. There is no known limit to the number of conversion operators in $fscanf or $sscanf.
Reading pattern files
This first instance shows how to read input stimulus from a text file.This is the pattern file - read_pattern.pat , included in the examples directory:
// This is a pattern file // time bin dec hex x: 001 1 1 xx.0: 010 20 020 50.02: 111 5 FFF 62.345: 100 iv DEADBEEF 75.789: 30 two ZzZzZzZzNote that the binary and hexadecimal values have X and Z values, merely these are not immune in the decimal values. Y'all tin use white space when formatting your file to get in more than readable. Lastly, any line beginning with a / is treated as a annotate.
The module read_pattern.v reads the time for the next pattern from an ASCII file. It and so waits until the absolute time specified in the input file, and reads the new values for the input signals (bin, dec, hex). The fourth dimension in the file is a real value and, when used in a delay, is rounded according to the timescale directive. Thus the time 75.789 is rounded to 75.79 ns.
`timescale 1ns / x ps `ascertain EOF 32'hFFFF_FFFF `define NULL 0 `define MAX_LINE_LENGTH 1000 module read_pattern; integer file, c, r; reg [3:0] bin; reg [31:0] december, hex; real real_time; reg [viii*`MAX_LINE_LENGTH:0] line; /* Line of text read from file */ initial begin : file_block $timeformat(-9, 3, "ns", six); $brandish("time bin decimal hex"); file = $fopenr("read_pattern.pat"); if (file == `NULL) // If fault opening file disable file_block; // Just quit c = $fgetc(file); while (c != `EOF) begin /* Cheque the first graphic symbol for comment */ if (c == "/") r = $fgets(line, `MAX_LINE_LENGTH, file); else begin // Push the character dorsum to the file and then read the next time r = $ungetc(c, file); r = $fscanf(file," %f:\n", real_time); // Wait until the absolute time in the file, and then read stimulus if ($realtime > real_time) $display("Error - accented fourth dimension in file is out of club - %t", real_time); else #(real_time - $realtime) r = $fscanf(file," %b %d %h\n",bin,dec,hex); end // if c else c = $fgetc(file); cease // while non EOF r = $fcloser(file); stop // initial // Display changes to the signals always @(bin or dec or hex) $display("%t %b %d %h", $realtime, bin, dec, hex); endmodule // read_pattern Comparison outputs with expected results
The following model, compare.v , reads a file containing both stimulus and expected results. The input signals are toggled at the beginning of a clock cycle and the output is compared just before the terminate of the bike. `define EOF 32'hFFFF_FFFF `define Zippo 0 `ascertain MAX_LINE_LENGTH 1000 module compare; integer file, r; reg a, b, expect, clock; wire out; reg [`MAX_LINE_LENGTH*eight:1]; parameter cycle = 20; initial begin : file_block $display("Time Stim Expect Output"); clock = 0; file = $fopenr("compare.pat"); if (file == `NULL) disable file_block; r = $fgets(line, MAX_LINE_LENGTH, file); // Skip comments r = $fgets(line, MAX_LINE_LENGTH, file); while (!$feof(file)) begin // Look until rising clock, read stimulus @(posedge clock) r = $fscanf(file, " %b %b %b\n", a, b, expect); // Wait only before the finish of wheel to do compare #(cycle - one) $display("%d %b %b %b %b", $stime, a, b, expect, out); $strobe_compare(expect, out); end // while non EOF r = $fcloser(file); $finish; finish // initial ever #(cycle / 2) clock = !clock; // Clock generator and #4 (out, a, b); // Circuit nether test endmodule // compare
Reading script files
Sometimes a detailed simulation model for a device is not available, such as a microprocessor. Equally a substitute, you can write a motorbus-functional model which reads a script of passenger vehicle transactions and performs these actions. The following, script.v , reads a file with commands plus data values. `define EOF 32'hFFFF_FFFF `ascertain Zippo 0 module script; integer file, r; reg [80*8:one] command; reg [31:0] addr, information; initial begin : file_block clock = 0; file = $fopenr("script.txt"); if (file == `Zippo) disable file_block; while (!$feof(file)) brainstorm r = $fscanf(file, " %s %h %h \northward", command, addr, data); case (command) "read": $display("READ mem[%h], await = %h", addr, information); "write": $display("WRITE mem[%h] = %h", addr, data); default: $brandish("Unknown control '%0s'", command); endcase end // while not EOF r = $fcloser(file); end // initial endmodule // scriptThe file script.txt is the script read by the in a higher place model:
read ix 0 write 300a feedface read 2FF xxxxxxxx bad
Reading data files into memories
Reading a formatted ASCII file is easy with the organisation tasks. The post-obit is an example of reading a binary file into a Verilog memory. $fread can also read a file 1 word at a time and copy the word into memory, but this is about 100 times slower than using $fread to read the unabridged array directly.This is the file load_mem.v
`define EOF 32'HFFFF_FFFF `ascertain MEM_SIZE 200_000 module load_mem; integer file, i; reg [seven:0] mem[0:`MEM_SIZE]; reg [eighty*8:1] file_name; initial begin file_name = "data.bin"; file = $fopenr(file_name); i = $fread(file, mem[0]); $display("Loaded %0d entries \n", i); i = $fcloser(file); $finish; end endmodule // load_mem The file data.bin contains the 200 binary values 0 to 199. Y'all can look at the plan information.c which generated the file. To dump out the binary file in Unix utilize the command od data.bin Linking with VCS
To use the file-read organization functions with Chronologic VCS, you will need to:- Compile read.c with the control:
- Compile and your Verilog model with:
cc -c read.c -I$VCS_HOME/sparc/lib
On the Dec/Alpha use
cc -c read.c -I$VCS_HOME/alpha/lib -taso -xtaso_short
% vcs load_mem.v read.o -P read_pli.tab -R Chronologic Simulation VCS Release 2.iv Copyright Chronologic Simulation 1991-1994. All Rights Reserved. This Licensed Software contains Confidential and proprietary information which is the property of Chronologic Simulation Compiling load_mem.v Top Level Modules: load_mem ( cd csrc ; brand -f Makefile DEFAULT_RUNTIME=Truthful product ) ../simv up to appointment Running simv -Five -a vcs.compile.log Chronologic Simulation VCS simulator copyright 1991-1994 Chronologic Simulation VCS simulator contains proprietary information. Compiler version two.4; runtime version 2.iv Loaded 200 entries $stop at time 0 Scope: load_mem File: load_mem.5 Line: thirteen cli_0 >
Linking with Verilog-Twoscore
To use the file-read system functions with Verilog-Forty, yous will need to:- Change veriuser.c to point to the organisation functions in read.c . You should copy these two files into your current directory from the examples directory.
- Blazon vconfig to generate a script to link Verilog-Twoscore. Use the following table to cull your responses.
Running vconfig | |
Prompt issued from vconfig : | You type: |
| Delight choose a platform | i, ii, 3, or 4 |
| Delight enter the name of the output script | cr_vlog_read |
| Please choose a target | 1 |
| What exercise you want to proper noun the Verilog-XL target? | verilog_read |
| Do you want to compile for the Verilog-Xl environment? | return |
| Exercise you lot want to include the dynamic LAI interface? | return |
| Exercise yous desire to include STATIC LOGIC AUTOMATION models in this executable? | return |
| Do y'all want to include the LMSI HARDWARE MODELER interface software in this executable? | render |
| Do you want to include the Verilog Mixed-Indicate interface software in this executable? | return |
| Do you lot want to include the CDC in this Verilog-Xl? | return |
| Do you lot want to include the Standard Delay File Annotator in this executable? | return |
| The user template file 'veriuser.c' must e'er be included in the link argument. What is the path name of this file? | ./veriuser.c |
| Delight list any other user files to be linked with this Verilog-Twoscore ... terminating with a single '.' | ./read.c . (menstruum) |
- Add the switch -Dverilogxl to cr_vlog to compile read.c
- Run cr_vlog_read and link Verilog-XL, producing the new executable verilog_read.
- Run the new executable and simulate your models with calls to the read functions.
- You should run across the following printed when you lot run verilog_read to simulate the model load_mem.v :
% ./verilog_read load_mem.v VERILOG-XL 2.1.12 Jun 21, 1995 xiv:55:32 Copyright (c) 1994 Cadency Design Systems, Inc. All Rights Reserved. . . . <<< Routines for file read linked in >> Compiling source file "load_mem.v" Highest level modules: load_mem Loaded 200 entries L13 "load_mem.v": $cease at simulation time 0 Type ? for help C1>
If you feel any difficulty in downloading the source file delight e-mail Rajesh Bawankule
Get dorsum to Alternate Verilog FAQ Page
Source: https://www.angelfire.com/in/verilogfaq/pli.html
0 Response to "Read Binary Data From .txt to Array in Verilog"
Post a Comment