library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.all;
use IEEE.std_logic_unsigned.all;
entity counter is
Port ( clk : in STD_LOGIC;
reset : in STD_LOGIC;
button : in STD_LOGIC;
count : out STD_LOGIC_VECTOR (6 downto 0)
);
end counter;
architecture Behavioral of counter is
signal debounced_button : std_logic;
signal prev_debounced_button : std_logic := '0';
signal counter_value : unsigned(6 downto 0) := (others => '0');
begin
-- Debounce the button signal using a rising edge detector
process (clk)
begin
if rising_edge(clk) then
if button = '1' and prev_debounced_button = '0' then
debounced_button <= '1';
else
debounced_button <= '0';
end if;
prev_debounced_button <= debounced_button;
end if;
end process;
-- Count up when the button is pressed
process (clk, reset)
begin
if reset = '1' then
counter_value <= (others => '0');
elsif rising_edge(clk) then
if debounced_button = '1' then
if counter_value = 100 then
counter_value <= (others => '0');
else
counter_value <= counter_value + 1;
end if;
end if;
end if;
end process;
-- Convert the counter value to a std_logic_vector for output
count <= std_logic_vector(counter_value);
end Behavioral;
——test bench:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.all;
entity counter_tb is
end counter_tb;
architecture Behavioral of counter_tb is
component counter
Port ( clk : in STD_LOGIC;
reset : in STD_LOGIC;
button : in STD_LOGIC;
count : out STD_LOGIC_VECTOR (6 downto 0)
);
end component;
signal clk : std_logic := '0';
signal reset : std_logic := '0';
signal button : std_logic := '0';
signal count : std_logic_vector(6 downto 0);
-- Stimulus process to generate clock and input signals
begin
uut: counter port map (
clk => clk,
reset => reset,
button => button,
count => count
);
clk_gen: process
begin
clk <= '0';
wait for 5 ns;
clk <= '1';
wait for 5 ns;
end process clk_gen;
stim_proc: process
begin
-- hold reset state for 100 ns.
reset <= '1';
wait for 20 ns;
reset <= '0';
wait;
end process;
process
begin
button <= '0';
wait for 40ns;
button <='1';
wait for 40ns;
button <= '0';
wait for 40ns;
button <='1';
wait for 40ns;
button <= '0';
wait for 40ns;
button <='1';
wait for 40ns;
end process;
end Behavioral;