We use $readmemh to quickly load data into memory from a file. This helps us test designs with real data without typing it all in.
0
0
Memory initialization with $readmemh in Verilog
Introduction
When you want to load a list of values into a memory block before simulation starts.
When testing a design that needs specific input data stored in memory.
When you want to reuse the same data for multiple tests without rewriting it.
When you have large memory content that is easier to keep in a separate file.
When you want to simulate ROM or RAM contents initialized from a hex file.
Syntax
Verilog
$readmemh("filename.hex", memory_array);The filename is a text file with hex values, one per line or space separated.
The memory_array is the Verilog memory variable you want to fill.
Examples
This loads hex data from
data.hex into the memory array mem.Verilog
$readmemh("data.hex", mem);This loads data from
init.hex into my_memory starting at index 0 up to 15.Verilog
$readmemh("init.hex", my_memory, 0, 15);
Sample Program
This example shows a small memory of 4 bytes. It loads hex values from memdata.hex into mem. Then it prints each value.
Verilog
module test_mem_init(); reg [7:0] mem [0:3]; integer i; initial begin $readmemh("memdata.hex", mem); for (i = 0; i < 4; i = i + 1) begin $display("mem[%0d] = %h", i, mem[i]); end end endmodule
OutputSuccess
Important Notes
The hex file should contain valid hex numbers matching the memory width.
If the file is missing or has errors, simulation may show warnings or load zeros.
You can also use $readmemb to load binary data instead of hex.
Summary
$readmemh loads hex data from a file into a memory array.
It is useful for initializing memory before simulation starts.
Make sure the file format matches your memory size and data width.