Skip to main content

32-bit counter and test bench

How could this VHDL counter and its test bench be improved? I am interested in anything you see that could be done better, but especially in the test bench:

  • Is wait for 10 ns better or worse than any other time delay?
  • The test is very minimal. Should it do more?

counter32.vhdl:

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity counter32 is
  port (
    clk: in std_ulogic;
    ena: in std_ulogic;
    rst: in std_ulogic;
    q  : out std_ulogic_vector(31 downto 0));
end entity;

architecture rtl of counter32 is

  signal count : unsigned(31 downto 0);

begin

  process(clk, rst)
  begin
    if rst = '1' then
      count <= X"00000000";
    elsif rising_edge(clk) then
      if ena = '1' then
        count <= count + 1;
      end if;
    end if;
  end process;

  q <= std_ulogic_vector(count);

end architecture;

counter32_tb.vhdl:

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity counter32_tb is
end counter32_tb;

architecture tb of counter32_tb is
  
  component counter32
    port (
      clk: in std_ulogic;
      ena: in std_ulogic;
      rst: in std_ulogic;
      q  : out std_ulogic_vector(31 downto 0));
  end component;
  
  signal clk: std_ulogic;
  signal ena: std_ulogic;
  signal rst: std_ulogic;
  signal q  : std_ulogic_vector(31 downto 0);

begin
  
  dut : counter32 port map (
    clk => clk,
    ena => ena,
    rst => rst,
    q => q);
  
  process
  begin

    -- Reset
    clk <= '0';
    ena <= '1';
    rst <= '1';
    wait for 10 ns;
    rst <= '0';
    wait for 10 ns;

    -- Counts on clock leading edge if enabled
    clk <= '1';
    wait for 10 ns;
    assert q = x"00000001";

    -- Does not count on clock trailing edge
    clk <= '0';
    wait for 10 ns;
    assert q = x"00000001";

    -- Does not count when not enabled
    ena <= '0';
    clk <= '1';
    wait for 10 ns;
    assert q = x"00000001";

    -- Clears on reset
    rst <= '1';
    wait for 10 ns;
    assert q = x"00000000";

    wait;

  end process;

end tb;

Shell script to run the test bench in GHDL:

OPTS=--workdir=build
ghdl -a ${OPTS} *.vhdl
ghdl -e ${OPTS} counter32_tb
ghdl -r ${OPTS} counter32_tb --vcd=counter32.vcd
Wayne Conrad
  • 3.3k
  • 1
  • 17
  • 38