VHDL Code:
  1.  
  2. library ieee ;
  3. use ieee.std_logic_1164.all;
  4. use ieee.std_logic_unsigned.all;
  5.  
  6. entity counter is
  7. port( clk: in std_logic;
  8. reset: in std_logic;
  9. enable: in std_logic;
  10. count: out std_logic_vector(3 downto 0)
  11. );
  12. end counter;
  13.  
  14. architecture behav of counter is
  15. signal pre_count: std_logic_vector(3 downto 0);
  16. begin
  17. process(clk, enable, reset)
  18. begin
  19. if reset = '1' then
  20. pre_count <= "0000";
  21. elsif (clk='1' and clk'event) then
  22. if enable = '1' then
  23. pre_count <= pre_count + "1";
  24. end if;
  25. end if;
  26. end process;
  27. count <= pre_count;
  28. end behav;
  29.  
  30.  
  31. --VHDL Test Bench for Counter:
  32.  
  33. library ieee ;
  34. use ieee.std_logic_1164.all;
  35. use ieee.std_logic_unsigned.all;
  36. use ieee.std_logic_textio.all;
  37. use std.textio.all;
  38.  
  39. entity counter_tb is
  40. end;
  41.  
  42. architecture counter_tb of counter_tb is
  43.  
  44. COMPONENT counter
  45. PORT ( count : OUT std_logic_vector(3 downto 0);
  46. clk : IN std_logic;
  47. enable: IN std_logic;
  48. reset : IN std_logic);
  49. END COMPONENT ;
  50.  
  51.  
  52.  
  53. SIGNAL clk : std_logic := '0';
  54. SIGNAL reset : std_logic := '0';
  55. SIGNAL enable : std_logic := '0';
  56. SIGNAL count : std_logic_vector(3 downto 0);
  57.  
  58. begin
  59.  
  60. dut : counter
  61. PORT MAP (
  62. count => count,
  63. clk => clk,
  64. enable=> enable,
  65. reset => reset );
  66.  
  67. clock : PROCESS
  68. begin
  69. wait for 1 ns; clk <= not clk;
  70. end PROCESS clock;
  71.  
  72. stimulus : PROCESS
  73. begin
  74. wait for 5 ns; reset <= '1';
  75. wait for 4 ns; reset <= '0';
  76. wait for 4 ns; enable <= '1';
  77. wait;
  78. end PROCESS stimulus;
  79.  
  80. monitor : PROCESS (clk)
  81. variable c_str : line;
  82. begin
  83. if (clk = '1' and clk'event) then
  84. write(c_str,count);
  85. assert false report time'image(now) &
  86. ": Current Count Value : " & c_str.all
  87. severity note;
  88. deallocate(c_str);
  89. end if;
  90. end PROCESS monitor;
  91.  
  92. end counter_tb;
  93.