A generic VHDL ROM with content initialisation from a file
This post describes how to code a technology-independent VHDL ROM memory and the use of an external file for setting the initial contents.
- library ieee ;
- use ieee.std_logic_1164.all;
- use ieee.numeric_Std.all;
- library std ;
- use std.textio.all;
- entity spROM is
- generic (initFile : string := "dummy_file_name.mif");
- port (
- CLK : in std_logic;
- ADDRESS : in std_logic_vector;
- DATAOUT : out std_logic_vector
- );
- end entity spROM;
- architecture arcspROM of spROM is
- type romType is array(0 to 2**ADDRESS'length-1) of std_logic_vector(DATAOUT'length-1 downto 0);
- -- uses VHDL 2008 hread
- impure function initRomFromFile return romType is
- file data_file : text open read_mode is initFile;
- variable data_fileLine : line;
- variable ROM : romType;
- begin
- for I in romType'range loop
- readline(data_file, data_fileLine);
- hread(data_fileLine, ROM(I));
- end loop;
- return ROM;
- end function;
- signal rom : romType := initRomFromFile;
- attribute rom_style : string;
- attribute rom_style of rom : signal is "block";
- begin
- process (CLK)
- begin
- if (CLK'event and CLK = '1') then
- DATAOUT <= rom(to_integer(unsigned(ADDRESS)));
- end if;
- end process;
- end architecture arcspROM;
Listing 2
A VHDL impure function is used so that it can reference the file name that is provided as a generic. Note also how the number of elements
in the std_logic_vectors for ADDRESS and DATAOUT are not specified - they will be "inherited" from the top level file that instantiates the ROM.
The spROM module can then be instantiated in a higher-level VHDL file like this:
- library ieee ;
- use ieee.std_logic_1164.all;
- entity top_mem is
- port (
- CLK : in std_logic;
- ADDRESS : in std_logic_vector(3 downto 0);
- DATAOUT : out std_logic_vector(15 downto 0)
- );
- end entity top_mem;
- architecture arc_top_mem of top_mem is
- component spROM is
- generic (initFile : string := "dummy_file_name.mif");
- port (
- CLK : in std_logic;
- ADDRESS : in std_logic_vector;
- DATAOUT : out std_logic_vector );
- end component spROM_16;
- begin
- U0 : spROM
- generic map (initFile => "my_init_file.mif")
- port map (
- CLK => CLK,
- ADDRESS => ADDRESS,
- DATAOUT => DATAOUT );
- end architecture arc_top_mem;
Listing 3
A zip archive that includes the VHDL source files and an example memory initialisation file is available here.