-- Sample VHDL — samplefiles.com
-- An up-counter with synchronous reset, enable and an overflow flag.
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity counter is
  generic (WIDTH : positive := 8);
  port (
    clk      : in  std_logic;
    rst      : in  std_logic;
    en       : in  std_logic;
    count    : out unsigned(WIDTH - 1 downto 0);
    overflow : out std_logic
  );
end entity counter;

architecture rtl of counter is
  constant MAX_VALUE : unsigned(WIDTH - 1 downto 0) := (others => '1');
  signal value : unsigned(WIDTH - 1 downto 0) := (others => '0');
begin
  process (clk)
  begin
    if rising_edge(clk) then
      if rst = '1' then
        value <= (others => '0');
      elsif en = '1' then
        value <= value + 1;
      end if;
    end if;
  end process;

  count    <= value;
  overflow <= '1' when en = '1' and value = MAX_VALUE else '0';
end architecture rtl;
