我们平常所用的按键为机械弹性开关,由于触点的弹性作用,按键在闭合时不会马上稳定的接通,而是有一段时间的抖动,在断开时也不会立即断开。抖动时间由按键的机械特性所决定,一般为5ms~10ms。所以我们在做按键检测时都要加一个消抖的过程。按键消抖主要有两种方案:一是硬件消抖;二是软件消抖。下面结合一个例程来看看老外是如何实现软件消抖的。
entity top is
Port ( btn_0 : in STD_LOGIC;
clk : in STD_LOGIC;
led : out STD_LOGIC);
end top;
architecture Behavioral of top is
constant CNTR_MAX : std_logic_vector(15 downto 0) := (others => '1');
signal btn0_cntr : std_logic_vector(15 downto 0) := (others => '0');
signal led_r : std_logic := '0';
signal btn0_reg : std_logic := '0';
begin
btn0_debounce_process : process (CLK)
begin
if (rising_edge(CLK)) then
if (btn0_cntr = CNTR_MAX) then
btn0_reg <= not(btn0_reg);
end if;
end if;
end process;
btn0_counter_process : process (CLK)
begin
if (rising_edge(CLK)) then
if ((btn0_reg = '1') xor (btn_0 = '1')) then
if (btn0_cntr = CNTR_MAX) then
btn0_cntr <= (others => '0');
else
btn0_cntr <= btn0_cntr + 1;
end if;
else
btn0_cntr <= (others => '0');
end if;
end if;
end process;
process(btn0_reg)
begin
if rising_edge(btn0_reg) then
led_r <= not (led_r);
end if;
end process;
led <= led_r;
end Behavioral;
constant CNTR_MAX : std_logic_vector(15 downto 0) := (others => '1');
signal btn0_cntr : std_logic_vector(15 downto 0) := (others => '0');
signal led_r : std_logic := '0';
signal btn0_reg : std_logic := '0';
begin
btn0_debounce_process : process (CLK)
begin
if (rising_edge(CLK)) then
if (btn0_cntr = CNTR_MAX) then
btn0_reg <= not(btn0_reg);
end if;
end if;
end process;
btn0_counter_process : process (CLK)
begin
if (rising_edge(CLK)) then
if ((btn0_reg = '1') xor (btn_0 = '1')) then
if (btn0_cntr = CNTR_MAX) then
btn0_cntr <= (others => '0');
else
btn0_cntr <= btn0_cntr + 1;
end if;
else
btn0_cntr <= (others => '0');
end if;
end if;
end process;
process(btn0_reg)
begin
if rising_edge(btn0_reg) then
led_r <= not (led_r);
end if;
end process;
led <= led_r;
end Behavioral;
一般人的做法是:当第一次检测到按键被按下后,执行一个延时程序,产生一个5ms~10ms的延时程序,然后再一次检测按键的状态,如果仍保持按键闭合状态电平,则认为确实有按键按下。这种办法不失为一种不错的解决方案,但是不同按键的机械特性不同,就算是同一型号按键机械特性或多或少也会有所不同,这样一来,延时时间不好确定。而上面的这段代码很好的解决了这一问题,下面我们来具体分析一下。当有按键按下
即btn_0 = '1',计数器启动开始计数,并且不断检测按键的状态。如果是抖动,计数器会被清零;如果按键闭合状态时的电平保持一段时间不发生变化,我们就认为当前有按键按下。同理,按键释放时也会执行类似的过程。按上述分析,我们会得到如下结论:btn0_reg出现上升沿代表有按键按下。上述例程的实验现象是:随着按键的按下LED交替点亮熄灭。