MIF_Gen - A Matlab Utility
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | %------------------------------------------- % 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\n', '-- Generated by mif_gen Matlab script'); fprintf( fileID, '%s\n\n', '-- FPGA SITE - https://fpgasite.blogspot.com'); fprintf( fileID, '%s%d%s\n', 'WIDTH=', word_size, ';'); fprintf( fileID, '%s%d%s\n\n', 'DEPTH=', ram_size, ';'); fprintf( fileID, '%s\n', 'ADDRESS_RADIX=HEX;'); fprintf( fileID, '%s\n\n', 'DATA_RADIX=HEX;'); fprintf( fileID, '%s\n', 'CONTENT BEGIN'); % data format fdata = int2str(word_size/4); faddr = int2str(log2(ram_size)/4); format_str = strcat(' %0', faddr, 'X : %0', fdata, 'X;\n'); % 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\n', '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 Altera .mif 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.
This utility is available at Github
Comments
Post a Comment