Search code examples
vhdlmodelsim

Is there a way to print the values of a signal to a file from a modelsim simulation?


I need to get the values of several signals to check them against the simulation (the simulation is in Matlab). There are many values, and I want to get them in a file so that I could run it in a script and avoid copying the values by hand.

Is there a way to automatically print the values of several signals into a text file?

(The design is implemented in VHDL)


Solution

  • First make functions that convert std_logic and std_logic_vector to string like:

    function to_bstring(sl : std_logic) return string is
      variable sl_str_v : string(1 to 3);  -- std_logic image with quotes around
    begin
      sl_str_v := std_logic'image(sl);
      return "" & sl_str_v(2);  -- "" & character to get string
    end function;
    
    function to_bstring(slv : std_logic_vector) return string is
      alias    slv_norm : std_logic_vector(1 to slv'length) is slv;
      variable sl_str_v : string(1 to 1);  -- String of std_logic
      variable res_v    : string(1 to slv'length);
    begin
      for idx in slv_norm'range loop
        sl_str_v := to_bstring(slv_norm(idx));
        res_v(idx) := sl_str_v(1);
      end loop;
      return res_v;
    end function;
    

    Using the bit-wise format has the advantage that any non-01 values will show with the exact std_logic value, which is not the case for e.g. hex presentation.

    Then make process that writes the strings from std_logic and std_logic_vector to file for example at rising_edge(clk) like:

    library std;
    use std.textio.all;
    ...
    process (clk) is
      variable line_v   : line;
      file     out_file : text open write_mode is "out.txt";
    begin
      if rising_edge(clk) then
        write(line_v, to_bstring(rst) & " " & to_bstring(cnt_1) & " " & to_bstring(cnt_3));
        writeline(out_file, line_v);
      end if;
    end process;
    

    The example above uses rst as std_logic, and cnt_1 and cnt_3 as std_logic_vector(7 downto 0). The resulting output in "out.txt" is then:

    1 00000000 00000000
    1 00000000 00000000
    1 00000000 00000000
    0 00000000 00000000
    0 00000001 00000011
    0 00000010 00000110
    0 00000011 00001001
    0 00000100 00001100
    0 00000101 00001111
    0 00000110 00010010