Many times I find myself in the need of generating data for testing. We need data for verification, either done on simulation or on the real target.

One easy way to test our system is to generate data vectors on RAM. Altera RAM IP includes the ability to initialize RAM contents during power-up by means of a .hex file.

One problem of the .hex file format is that it is quite unreadable for humans. Altera came to our rescue with the .mif format, which is text based and very easy to understand.

The application I present below initializes a memory (generating an .hex file). The size and width of the memory are parameters. The Matlab application generates both a init_mem.mif and a init_mem.hex file.

%——————————————- % Generate Parameters ram_size = 256; % In words word_size = 16; % Can be 8, 16, 32, etc. %——————————————- % generate vector with random values within % a defined range min_v = 100; max_v = 20000; % Check values and calculate range if (min_v < 0) min_v = 0; end max_val = 2^word_size-1; if (max_v > max_val) max_v = max_val; end range_v = max_v – min_v; values = (randi(range_v – 1, ram_size, 1)) + min_v; %——————————————- % Open mif file for write fileID = fopen (‘init_mem.mif’, ‘w’); fprintf ( fileID, ‘%s

’, ‘– Generated by mif_gen Matlab script’); fprintf ( fileID, ‘%s



’, ‘– FPGA’er – https://fpgaer.wordpress.com’); fprintf ( fileID, ‘%s%d%s

’, ‘WIDTH=’, word_size, ‘;’); fprintf ( fileID, ‘%s%d%s



’, ‘DEPTH=’, ram_size, ‘;’); fprintf ( fileID, ‘%s

’, ‘ADDRESS_RADIX=HEX;’); fprintf ( fileID, ‘%s



’, ‘DATA_RADIX=HEX;’); fprintf ( fileID, ‘%s

’, ‘CONTENT BEGIN’); % data format fdata = int2str (word_size/4); faddr = int2str ( log2 (ram_size)/4); format_str = strcat (‘ %0’, faddr, ‘X : %0’, fdata, ‘X;

’); % write values to file idx = 0; for ii=1:ram_size fprintf ( fileID, format_str, idx, values(idx+1)); idx = idx+1; end fprintf ( fileID, ‘%s

’, ‘END;’); fclose ( fileID); %——————————————- % Convert to HEX cmd = ‘D:\altera_lite\15.1\quartus\bin64\mif2hex keys.mif init_mem.hex’; system(cmd);

Lines 26 to 33 generate the Intel-Altera .mif file header. Lines 36 to 38 define the format for writing the data rows with the fprintf command, based on the memory size and width.

Lines 41 to 47 actually put the values on each line of the file.

Lines 51 and 52 generate the .hex file via a system call using Altera’s mif2hex utility. You will need to change the path on line 72 to the actual location of your Quartus installation.

You can download this utility at Github