Chapter 7: VHDL: Sequential Design, Arithmetic and Testbenches¶
The previous chapter gave the structure of VHDL. This chapter builds the same designs that Chapters 4 and 5 built in Verilog, in VHDL: flip-flops and registers, a counter, a state machine with named states, arithmetic on vectors, a parameterised adder, an ALU and a self-checking testbench. Because the ideas are already familiar, much of the work is new spelling, and the chapter ends with a table that translates the constructs of the two languages one by one. Examples assume VHDL-2008 (with GHDL: --std=08), which provides process(all) and to_string.
7.1 Clocked logic¶
Synchronous hardware updates on a clock edge. In VHDL you write a process sensitive to the clock and gate its body with rising_edge(clk). Everything assigned inside that edge test becomes a flip-flop.
The D flip-flop¶
library ieee;
use ieee.std_logic_1164.all;
entity dff is
port ( clk, d : in std_logic;
q : out std_logic );
end entity dff;
architecture rtl of dff is
begin
process (clk)
begin
if rising_edge(clk) then -- captures d on the 0 -> 1 edge
q <= d;
end if;
end process;
end architecture rtl;
A register with asynchronous reset and load enable¶
library ieee;
use ieee.std_logic_1164.all;
entity reg8 is
port (
clk, rst_n, load : in std_logic;
d : in std_logic_vector(7 downto 0);
q : out std_logic_vector(7 downto 0)
);
end entity reg8;
architecture rtl of reg8 is
begin
process (clk, rst_n) -- rst_n is asynchronous, so it is listed
begin
if rst_n = '0' then -- active-low reset wins
q <= (others => '0');
elsif rising_edge(clk) then
if load = '1' then -- synchronous load enable
q <= d;
end if; -- otherwise: hold (no assignment)
end if;
end process;
end architecture rtl;
"Hold" means no assignment. When load = '0' we assign nothing to q, and in a clocked process that correctly infers a flip-flop with an enable, not a latch. The reset is in the sensitivity list because it must act the instant it asserts, independent of the clock; load is only sampled on the clock edge, inside the rising_edge branch, which the process reaches only on that edge.
An 8-bit counter¶
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity counter8 is
port (
clk, rst_n, en : in std_logic;
count : out std_logic_vector(7 downto 0)
);
end entity counter8;
architecture rtl of counter8 is
signal cnt : unsigned(7 downto 0); -- the internal counter is 'unsigned'
begin
process (clk, rst_n)
begin
if rst_n = '0' then
cnt <= (others => '0');
elsif rising_edge(clk) then
if en = '1' then
cnt <= cnt + 1; -- wraps 255 -> 0 automatically
end if;
end if;
end process;
count <= std_logic_vector(cnt); -- convert the type for the output port
end architecture rtl;
The counter keeps an internal unsigned signal so that + 1 is defined, and converts it for the port in a concurrent assignment. This is the usual pattern: arithmetic on the numeric type inside, plain bit vectors on the interface.
7.2 A state machine with an enumerated type¶
State machines are where VHDL shines. Define an enumerated type for the states, so that the code reads by name and not by bit pattern, and let the synthesiser choose the encoding. The classic style uses two processes: one clocked for the state register, and one combinational for the next state and the outputs.
This machine is the serial "101" recognizer of Chapter 4, in its Mealy form: found is raised for one cycle in the same cycle in which the final 1 of the pattern is present on din, and three states suffice.
library ieee;
use ieee.std_logic_1164.all;
entity seq101 is
port (
clk, rst_n : in std_logic;
din : in std_logic;
found : out std_logic
);
end entity seq101;
architecture rtl of seq101 is
type state_t is (S_IDLE, S_GOT1, S_GOT10); -- enumerated states
signal state, next_state : state_t;
begin
-- 1) state register: clocked
process (clk, rst_n)
begin
if rst_n = '0' then
state <= S_IDLE;
elsif rising_edge(clk) then
state <= next_state;
end if;
end process;
-- 2) next-state and output logic: combinational
process (all)
begin
next_state <= state; -- default: stay put
found <= '0'; -- default: no detection
case state is
when S_IDLE =>
if din = '1' then next_state <= S_GOT1; end if;
when S_GOT1 =>
if din = '0' then next_state <= S_GOT10;
else next_state <= S_GOT1; -- "11": still holding a 1
end if;
when S_GOT10 =>
if din = '1' then
found <= '1'; -- "101" seen
next_state <= S_GOT1; -- overlap: this 1 starts anew
else
next_state <= S_IDLE;
end if;
end case;
end process;
end architecture rtl;
The defaults at the top of the combinational process guarantee that every branch drives next_state and found; miss them and you infer an unwanted latch. They mean: "unless a case says otherwise, hold the state and output 0".
Example 7.1: tracing the Mealy detector
Feed the stream 1 0 1 0 1 1 0 1 from S_IDLE. In each row, the found column is the value of the combinational output during the cycle in which that bit is present.
| Bit | din |
State during the cycle | found |
State at the next edge |
|---|---|---|---|---|
| 1 | 1 | S_IDLE |
0 | S_GOT1 |
| 2 | 0 | S_GOT1 |
0 | S_GOT10 |
| 3 | 1 | S_GOT10 |
1 | S_GOT1 |
| 4 | 0 | S_GOT1 |
0 | S_GOT10 |
| 5 | 1 | S_GOT10 |
1 | S_GOT1 |
| 6 | 1 | S_GOT1 |
0 | S_GOT1 |
| 7 | 0 | S_GOT1 |
0 | S_GOT10 |
| 8 | 1 | S_GOT10 |
1 | S_GOT1 |
The detections occur on bits 3, 5 and 8, the same bits as in the Moore machine of Chapter 4, but each found is high one cycle earlier. The step from S_GOT10 with din = '1' goes to S_GOT1, not S_IDLE, because the 1 that completed 101 is also the start of a possible overlapping 101: this is what lets 1-0-1-0-1 fire twice.
7.3 Vector arithmetic with numeric_std¶
A std_logic_vector is just a bag of bits with no numeric meaning. To do arithmetic you interpret it as unsigned or signed from numeric_std, compute, and convert back. The conversions are:
| From | To | Function |
|---|---|---|
std_logic_vector |
unsigned |
unsigned(v) (a cast: the same bits) |
unsigned |
std_logic_vector |
std_logic_vector(u) |
unsigned or signed |
integer | to_integer(u) |
| integer | unsigned of \(N\) bits |
to_unsigned(i, N) |
| integer | signed of \(N\) bits |
to_signed(i, N) |
Overflow is silent
The sum of two 8-bit unsigned operands has 8 bits and wraps modulo 256, so the carry is lost: \(200 + 100 = 300\) appears as \(300 - 256 = 44\). To keep the carry, widen an operand first: ('0' & ua) + ('0' & ub) gives a 9-bit sum whose top bit is the carry out. The function resize also changes the width of unsigned and signed values.
7.4 Generics and generate¶
A generic parameterises an entity, here with the bit width, just as parameter does in Verilog. A for ... generate loop replicates hardware, so that we can chain \(N\) full adders into a ripple-carry adder. First, the one-bit building block:
library ieee;
use ieee.std_logic_1164.all;
entity full_adder is
port ( a, b, cin : in std_logic;
sum, cout : out std_logic );
end entity full_adder;
architecture rtl of full_adder is
begin
sum <= a xor b xor cin;
cout <= (a and b) or (a and cin) or (b and cin);
end architecture rtl;
Then the \(N\)-bit adder:
library ieee;
use ieee.std_logic_1164.all;
entity ripple_adder is
generic ( N : positive := 8 ); -- width parameter
port (
a, b : in std_logic_vector(N-1 downto 0);
cin : in std_logic;
sum : out std_logic_vector(N-1 downto 0);
cout : out std_logic
);
end entity ripple_adder;
architecture structural of ripple_adder is
signal carry : std_logic_vector(N downto 0); -- carry chain: N + 1 wires
begin
carry(0) <= cin;
gen_bits : for i in 0 to N-1 generate -- replicate N adders
fa : entity work.full_adder
port map (
a => a(i),
b => b(i),
cin => carry(i),
sum => sum(i),
cout => carry(i+1)
);
end generate gen_bits;
cout <= carry(N);
end architecture structural;
For synthesis you would normally write result <= std_logic_vector(unsigned(a) + unsigned(b)) and let the tool build the adder; the structural version shows how generate and hierarchy work, the same ingredients used for shift registers, systolic arrays and more.
7.5 A small ALU¶
An ALU puts arithmetic and logic behind a case on an operation select. This 8-bit ALU uses numeric_std for the arithmetic paths and reports a zero flag.
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity alu8 is
port (
a, b : in std_logic_vector(7 downto 0);
op : in std_logic_vector(2 downto 0); -- 3-bit operation code
result : out std_logic_vector(7 downto 0);
zero : out std_logic -- 1 when result = 0
);
end entity alu8;
architecture rtl of alu8 is
signal res : std_logic_vector(7 downto 0);
begin
process (all)
variable ua, ub : unsigned(7 downto 0);
begin
ua := unsigned(a);
ub := unsigned(b);
case op is
when "000" => res <= std_logic_vector(ua + ub); -- ADD
when "001" => res <= std_logic_vector(ua - ub); -- SUB
when "010" => res <= a and b; -- AND
when "011" => res <= a or b; -- OR
when "100" => res <= a xor b; -- XOR
when "101" => res <= std_logic_vector(ua + 1); -- INC A
when "110" => res <= std_logic_vector(shift_left(ua, 1)); -- A << 1
when others => res <= (others => '0'); -- default
end case;
end process;
result <= res;
zero <= '1' when res = "00000000" else '0';
end architecture rtl;
The variables ua and ub hold the converted inputs: scratch work inside one process, as Section 6.5 recommends. Note that every branch assigns res, so no latch is inferred. Like the Verilog ALU of Chapter 5, this one loses the carry unless the operands are widened first.
7.6 A self-checking testbench¶
A testbench is a top-level entity with no ports. It instantiates the design (the DUT), drives its inputs from a stimulus process, and checks the outputs with assert and report. Testbenches use the full, non-synthesizable language: wait, delays, loops and text output.
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity alu8_tb is -- a testbench has no ports
end entity alu8_tb;
architecture sim of alu8_tb is
signal a, b, result : std_logic_vector(7 downto 0);
signal op : std_logic_vector(2 downto 0);
signal zero : std_logic;
begin
-- instantiate the device under test
dut : entity work.alu8
port map ( a => a, b => b, op => op, result => result, zero => zero );
-- stimulus and checking
stim : process
-- helper: apply one operation and check the expected result
procedure check (
constant av, bv : in integer;
constant opv : in std_logic_vector(2 downto 0);
constant exp : in integer
) is
begin
a <= std_logic_vector(to_unsigned(av, 8));
b <= std_logic_vector(to_unsigned(bv, 8));
op <= opv;
wait for 10 ns; -- let the combinational logic settle
assert to_integer(unsigned(result)) = exp
report "FAIL: op=" & to_string(opv) &
" got " & integer'image(to_integer(unsigned(result))) &
" exp " & integer'image(exp)
severity error;
end procedure;
begin
check(10, 5, "000", 15); -- 10 + 5 = 15
check(10, 5, "001", 5); -- 10 - 5 = 5
check(12, 10, "010", 8); -- 12 AND 10 = 8
check( 6, 3, "100", 5); -- 6 XOR 3 = 5
check( 4, 0, "110", 8); -- 4 << 1 = 8
report "All ALU tests completed." severity note;
wait; -- suspend forever: the simulation ends
end process;
end architecture sim;
The wait statement has several forms. wait for 10 ns; waits an amount of time; wait until rising_edge(clk); waits for an event; and a bare wait; suspends the process permanently, which lets the simulation run down to completion. The values in the checks are easy to verify by hand: \(12 = 1100\) and \(10 = 1010\), so their AND is \(1000 = 8\); \(6 \oplus 3 = 0110 \oplus 0011 = 0101 = 5\).
To run it with GHDL: ghdl -a --std=08 alu8.vhd alu8_tb.vhd, then ghdl -e --std=08 alu8_tb and ghdl -r --std=08 alu8_tb --wave=out.ghw, and open the waveform in GTKWave. Or paste both files into EDA Playground, choose a VHDL simulator, and open the waveform after the run.
7.7 Verilog and VHDL side by side¶
Coming from Verilog, the concepts map almost one to one; the syntax and the discipline differ.
| Concept | Verilog | VHDL |
|---|---|---|
| Module boundary | module m(...); ... endmodule |
entity m is port(...); end; plus architecture |
| 1-bit wire | wire w; |
signal w : std_logic; |
| Bus | wire [7:0] b; |
std_logic_vector(7 downto 0) |
| Continuous drive | assign y = a & b; |
y <= a and b; |
| Clocked block | always @(posedge clk) |
if rising_edge(clk) then |
| Blocking assignment (temporary) | x = ...; |
variable, x := ...; |
| Non-blocking assignment (register) | q <= d; |
signal assignment q <= d; |
| Multiplexer | case (sel) ... |
with sel select or case |
| Parameter | parameter N = 8; |
generic ( N : positive := 8 ); |
| Replication | generate ... endgenerate |
for i in ... generate |
| Constant literal | 8'hFF |
x"FF" or "11111111" |
The big philosophical split is that Verilog is loosely typed and permissive, and VHDL is strongly typed and strict. Verilog lets a width mismatch slide and truncates; VHDL refuses to compile until you make the conversion explicit. It costs more typing up front and gives fewer silent bugs later.
7.8 Common pitfalls¶
- Latch from a missing else or default. In a combinational process, if any path leaves a signal unassigned, the signal must remember its old value: a latch. Assign defaults at the top of the process, or give every
ifanelseand everycaseawhen others. - Multiple drivers. Two concurrent statements or processes that assign the same signal conflict, and
std_logicresolves the conflict to'X'. - Reading an
outport. In classic VHDL you cannot read a port of modeout. Use an internal signal and assign the port from it (as the counter did), use modebuffer, or rely on VHDL-2008, which relaxes the rule. - The wrong package for arithmetic. Mixing
numeric_stdwith the legacystd_logic_unsignedgives ambiguous overloads and "no feasible entry" errors. Picknumeric_stdand convert tounsignedorsignedexplicitly. - Lost carries. Arithmetic on equal-width operands wraps; widen first if the carry matters.
7.9 Summary¶
- Clocked logic is a process sensitive to the clock whose body is gated with
rising_edge(clk); an asynchronous reset is listed in the sensitivity list and tested first. - A register that is not assigned on some path holds; in a clocked process this is an enable, not a latch.
- Name state-machine states with an enumerated type, use two processes (state register; next state and outputs), and put defaults at the top of the combinational one.
- Do arithmetic through
numeric_std'sunsignedandsigned; convert on the way in and out; widen operands to keep a carry. - Generics parameterise entities;
for ... generatereplicates hardware. - A testbench is an entity with no ports; check results with
assertandreport; end the stimulus process with a barewait;. - The two languages express the same ideas. VHDL asks for explicit types and conversions; Verilog is terser and more permissive.
7.10 Exercises¶
Exercise 7.1 (the counter again, in VHDL). Rewrite the counter with load and enable of Exercise 4.1 in VHDL: entity, architecture, one clocked process, numeric_std arithmetic, a generic width. Then write a testbench that resets, enables for 10 clocks, loads 250, enables for 10 more clocks and then holds for three clocks, checking each step with assert. What values should it check?
Answer
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity counter_ld is
generic ( W : positive := 8 );
port ( clk, rst_n, load, en : in std_logic;
d : in std_logic_vector(W-1 downto 0);
q : out std_logic_vector(W-1 downto 0) );
end entity counter_ld;
architecture rtl of counter_ld is
signal cnt : unsigned(W-1 downto 0);
begin
process (clk, rst_n)
begin
if rst_n = '0' then
cnt <= (others => '0');
elsif rising_edge(clk) then
if load = '1' then
cnt <= unsigned(d);
elsif en = '1' then
cnt <= cnt + 1;
end if;
end if;
end process;
q <= std_logic_vector(cnt);
end architecture rtl;
The testbench:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity counter_ld_tb is
end entity counter_ld_tb;
architecture sim of counter_ld_tb is
signal clk : std_logic := '0';
signal rst_n : std_logic := '0';
signal load : std_logic := '0';
signal en : std_logic := '0';
signal d : std_logic_vector(7 downto 0) := (others => '0');
signal q : std_logic_vector(7 downto 0);
begin
dut : entity work.counter_ld
generic map ( W => 8 )
port map ( clk => clk, rst_n => rst_n, load => load, en => en, d => d, q => q );
clk <= not clk after 5 ns;
stim : process
procedure expect (constant exp : in integer; constant what : in string) is
begin
assert to_integer(unsigned(q)) = exp
report "FAIL " & what & ": got " & integer'image(to_integer(unsigned(q)))
& ", expected " & integer'image(exp)
severity error;
end procedure;
begin
wait for 12 ns;
rst_n <= '1'; en <= '1';
for i in 1 to 10 loop wait until rising_edge(clk); end loop;
wait for 1 ns;
expect(10, "after 10 counts");
load <= '1'; d <= std_logic_vector(to_unsigned(250, 8));
wait until rising_edge(clk); wait for 1 ns;
load <= '0';
expect(250, "after load");
for i in 1 to 10 loop wait until rising_edge(clk); end loop;
wait for 1 ns;
expect(4, "after 10 more counts (wrap)");
en <= '0';
for i in 1 to 3 loop wait until rising_edge(clk); end loop;
wait for 1 ns;
expect(4, "holding");
report "Counter test finished." severity note;
wait;
end process;
end architecture sim;
The values to check are 10, 250, 4 (because \(250 + 10 = 260\) and \(260 \bmod 256 = 4\)) and 4 again while held. They are the same as for the Verilog version.
Exercise 7.2. List three differences between the Verilog and the VHDL counter that you would notice when reading the two side by side.
Answer
(1) VHDL needs explicit types and conversions: the counter keeps an unsigned signal internally and converts it to std_logic_vector for the port, while Verilog adds to a reg directly. (2) VHDL separates the interface (entity) from the implementation (architecture), while Verilog has a single module. (3) VHDL is case-insensitive and more verbose; its clock condition is rising_edge(clk) against Verilog's @(posedge clk), and registers are signals updated when the process suspends, against Verilog's non-blocking assignment. Both produce the same flip-flops and the same wrap-around at 255.
Exercise 7.3. Evaluate: (a) to_integer(unsigned'("1010")); (b) to_unsigned(5, 4); (c) to_integer(signed'("1111")); (d) with ua and ub 8-bit unsigned values holding 200 (x"C8") and 100 (x"64"), the result of ua + ub and the 9-bit result of ('0' & ua) + ('0' & ub).
Answer
(a) "1010" read as an unsigned number is 10. (b) 5 in four bits is "0101". (c) "1111" read as a four-bit two's complement number is \(-1\). (d) \(\text{0xC8} = 200\) and \(\text{0x64} = 100\); the 8-bit sum is \(300 \bmod 256 = 44\) (x"2C"), with the carry lost, while the 9-bit sum is 300 ("1_0010_1100"), whose top bit is the carry.
Exercise 7.4. Trace the Mealy detector of Section 7.2 on the stream 0 1 1 0 1 0 1 and give the bits on which found is high.
Answer
From S_IDLE: bit 1 is 0, so the state stays S_IDLE. Bit 2 is 1: S_GOT1. Bit 3 is 1: stays S_GOT1. Bit 4 is 0: S_GOT10. Bit 5 is 1: found = 1, and the state is S_GOT1. Bit 6 is 0: S_GOT10. Bit 7 is 1: found = 1. So found is high on bits 5 and 7, two detections (the substrings 1-0-1 at bits 3-4-5 and 5-6-7 overlap at bit 5).
Exercise 7.5. Why does the case in the state machine of Section 7.2 not need a when others branch, when the case on op in the ALU does?
Answer
The state is an enumerated type with exactly three values, and the case lists all three, so it is exhaustive. The ALU's op is a std_logic_vector, which can hold 81 two-bit patterns (including 'X' and 'Z'), of which the case lists only a few, so when others is needed.
Exercise 7.6. Translate this Verilog fragment into VHDL, using signals and the numeric_std types: always @(posedge clk) if (en) acc <= acc + din; where acc and din are 8 bits.
Answer
signal acc : unsigned(7 downto 0) := (others => '0');
...
process (clk)
begin
if rising_edge(clk) then
if en = '1' then
acc <= acc + unsigned(din); -- din is std_logic_vector(7 downto 0)
end if;
end if;
end process;
The clock edge, the condition and the transfer map as in Section 2.4. din is converted to unsigned because + is defined for unsigned, and the result wraps modulo 256, as in the Verilog.