Generic downcounter

For synchronous logic, a timer and a counter are almost the same. After all, a timer counts clock units. That is why in many digital applications we see them called timer/counters.

The code below models a generic timer/counter.

For more information, including simulation and a timers’ block project, please look in the Timers block post.

  1. library ieee;
  2. use ieee.std_logic_1164.all;
  3. use ieee.numeric_std.all;
  4.  
  5. entity downcounter is
  6. generic (
  7. DATA_W : natural := 32
  8. );
  9. port (
  10. clk : in std_logic;
  11. rst : in std_logic;
  12.  
  13. -- inputs
  14. data_in : in std_logic_vector (DATA_W - 1 downto 0);
  15. load : in std_logic;
  16. en : in std_logic;
  17.  
  18. -- outputs
  19. data_out : out std_logic_vector (DATA_W - 1 downto 0);
  20. done : out std_logic
  21. );
  22. end downcounter;
  23.  
  24. architecture rtl of downcounter is
  25. signal counter_reg : unsigned (DATA_W - 1 downto 0);
  26.  
  27. begin
  28. counter_pr : process (clk, rst)
  29. begin
  30. if (rst = '1') then
  31. counter_reg <= (others => '0');
  32. done <= '0';
  33. elsif (rising_edge(clk)) then
  34. if (load = '1') then -- load counter
  35. counter_reg <= unsigned(data_in);
  36. done <= '0'; -- start a new countdown - deassert done signal
  37. elsif (en = '1') then -- is counting enabled?
  38. if (counter_reg = 0) then -- check if counter reached zero
  39. done <= '1'; -- set done output
  40. else
  41. counter_reg <= counter_reg - 1; -- decrement counter
  42. end if;
  43. end if;
  44. end if;
  45. end process;
  46.  
  47. data_out <= std_logic_vector(counter_reg);
  48.  
  49. end rtl;

 

 

The source code for the downcounter is available at Github

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s