这里介绍一种基于延时判断的按键消抖程序。首先,程序会一直检测按键是否按下,如果按下了就延迟一段是间再去判断,如果此时按键的状态没有改变,那么就认定这次按键的触发是人为触发的。否则,认为是误触发。
直接把代码贴出来吧。(也可以到我的资源页面进行下载按键消抖)
-----------------------------------------------------------------------------
-- ____ ____
-- - -\- -
-- -___- \ -
-- \ \ \-
-- \ \ Module: debounce
-- - - Filename: debounce.v
-- -___- -\ Purpose: Debounce push buttons.
-- \ \ - \
-- \___\-\___\
--
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
--
-- Module Description:
--
-- This module debounces the push button inputs.
--
-----------------------------------------------------------------------------
--
-- Port Definition:
--
-- Name Type Description
-- ============================= ====== ====================================
-- clk input System clock; the entire system is
-- synchronized to this signal, which
-- is distributed on a global clock
-- buffer and referred to as icap_clk.
--
-- noisy input Push button input.
--
-- clean output Debounced output.
--
-----------------------------------------------------------------------------
library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_arith.all;
use ieee.std_logic_unsigned.all;
library unisim;
use unisim.vcomponents.all;
-----------------------------------------------------------------------------
-- Entity
-----------------------------------------------------------------------------
entity debounce is
port (
clk : in std_logic;--时钟信号
reset : in std_logic; --复位信号,复位后按键输出为‘0’,计数值也复制为0
noisy : in std_logic;--按键输入
clean : out std_logic--按键输出
);
end entity debounce;
architecture xilinx of debounce is
signal db_count : std_logic_vector(15 downto 0);--延时计数信号
signal db_new : std_logic;--缓存按键的状态,用来比较一段时间后新的按键状态和就的按键状态是否一样
begin
process (clk)
begin
if (clk'event and clk='1') then
if (reset='1') then --复位对各个信号进行初始化
db_count <= x"0000";
db_new <= '0';
clean <= '0';
elsif(noisy /= db_new) then
--如果此时按键按下,则noisy为‘1’,与原来的db_new不一样,所以将新的状态‘1’赋
--给db_new。如果还没有技术器还没有计到‘FFFF’时,按键状态noisy又松开了,即noisy变为‘0’,说明是误触发。
db_new <= noisy;
db_count <= x"0000";--技术器设为‘0000’,从零开始计数。
elsif(db_count = x"FFFF") then --如果技术器可以计到‘FFFF’,说明按键被正确按下了,将按键的当前状态输出
clean <= db_new;
else
db_count <= db_count + '1';--计数器自加
end if;
end if;
end process;
end architecture xilinx;
仿真波形: