16

I have been looking at some Verilog testbench code that heavily uses $readmemh and $writememh.

I have a vague understanding that these functions basically read to and write from memory. What is their specific function and how do they work?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Alphaneo
  • 12,079
  • 22
  • 71
  • 89

1 Answers1

28

I agree its not too easy to find something about readmem/writemem. You can find a little bit here: https://www.fullchipdesign.com/readmemh.htm

Anyway there is not too much to say about these functions, the syntax is:

$readmem[hb]("File", ArrayName, StartAddr, EndAddr)
$writemem[hb]("File", ArrayName, StartAddr, EndAddr)

Verilog is very picky about the file format, the number of bit in the text file have to match the number of bits in the array.

I recommend you play around a little bit by defining an array, filling it up with data write it out with writememh/writememb and print it out afterwards.

Something like this should get you started (not tried out!).

integer i;
reg [7:0] memory [0:15]; // 8 bit memory with 16 entries

initial begin
    for (i=0; i<16; i++) begin
        memory[i] = i;
    end
    $writememb("memory_binary.txt", memory);
    $writememh("memory_hex.txt", memory);
end
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
danielpoe
  • 3,756
  • 23
  • 18
  • As well, the tools can be picky about finding the path. [Project F: FPGA Dev](https://projectf.io/posts/initialize-memory-in-verilog/) has some information on this. The 'fool proof' way is to provide a full path. But full paths are foolish. I believe that "File" can be supplied as a module parameter and often this might be a better mechanics. See: [Passing string as a parameter](https://stackoverflow.com/questions/23554080/passing-string-values-to-systemverilog-parameter). – artless noise Jan 03 '23 at 18:43
  • Another reference to the file format. [1364-2005 $readmemh](https://stackoverflow.com/questions/66824196/icarus-verilog-warning-readmemh-standard-inconsistency-following-1364-2005) where order in the file is important. Altera/Intel provide JTAG mechanics to update the table at run time ("In-System Modifiable Memories and Constants"). Eg. [Dual port ram](https://electronics.stackexchange.com/questions/481011/why-cant-dual-port-ram-be-read-out-using-the-quartus-in-system-memory-content-e) – artless noise Jan 03 '23 at 19:39
  • Also, the point about *very picky about the file format,*. You can only use 'readmemh()` when the bit size is a multiple of 4. Otherwise, you need a binary file. – artless noise Sep 01 '23 at 21:18