File I/O with TEXTIO
Procedures: readline, read, hread, oread, bread, writeline, write, hwrite, owrite, swrite (2008), file_open, file_close, endfile. Also used to initialize ROMs from files at elaboration time (synthesizable in most tools):
use std.textio.all;
use ieee.std_logic_textio.all; -- read/write for std_logic types (built into std_logic_1164 in 2008)
-- Read stimulus vectors and expected results from a file
stim_from_file : process
file vec_file : text open read_mode is "vectors.txt";
file result_file : text open write_mode is "results.txt";
variable l_in, l_out : line;
variable va, vb, vexp : std_logic_vector(7 downto 0);
variable sep : character;
begin
while not endfile(vec_file) loop
readline(vec_file, l_in);
next when l_in'length = 0 or l_in(1) = '#'; -- skip blank/comment lines
hread(l_in, va); read(l_in, sep); hread(l_in, vb); read(l_in, sep); hread(l_in, vexp);
a <= va; b <= vb;
wait for 10 ns;
write(l_out, string'("a=")); hwrite(l_out, va);
write(l_out, string'(" b=")); hwrite(l_out, vb);
write(l_out, string'(" y=")); hwrite(l_out, y);
if y /= vexp then write(l_out, string'(" FAIL")); end if;
writeline(result_file, l_out);
end loop;
file_close(vec_file); file_close(result_file);
wait;
end process;# a b expected
0A 05 0F
FF 01 00impure function init_rom(fname : string) return rom_t is
file f : text open read_mode is fname;
variable l : line; variable r : rom_t;
begin
for i in rom_t'range loop
readline(f, l); hread(l, r(i));
end loop;
return r;
end function;
signal rom : rom_t := init_rom("rom_init.hex");🧪 Part II Exercises
Implement an 8:1 multiplexer three ways (with/select, when/else, process with case) and verify they match.
Write a 4-bit ripple-carry adder structurally from full adders using for generate.
Design an 8-bit ALU with flags (zero, carry, overflow, negative) and an exhaustive testbench.
Build an up/down loadable counter with synchronous reset and enable; verify with a self-checking testbench.
Implement a debounced push-button with rising-edge detection.
Design a vending-machine FSM (Moore) accepting 5/10/25-cent coins; output "dispense" and change.
Implement a "1101" overlapping sequence detector as both Moore and Mealy machines; compare waveforms.
Write a package with log2ceil, reverse, to_bcd functions and use them in a design.
Create a generic-width shift register with parallel load and serial in/out using generics and generate.
Build a file-driven testbench for your ALU that reads vectors from a text file and writes a pass/fail report.