请尊重作者版权,转载请注明源地址http://www.cnblogs.com/connorzx/p/3548364.html
按键在按下的过程中通常会产生一段时间的抖动,为了消除这种抖动,一般采取两种方法。一种为硬件消抖,另一种为软件消抖。
硬件消抖是利用了RS锁存器的相关原理。如下图所示,开关在B处时,5处为低电平,1处为高电平。根据与非门“有零出一”的特点,6处为高电平,即2处为高电平。所以此时3处为低电平。当开关从B拨到A时,5处变为高电平,一旦1处出现低电平,输出将一直为高电平。(读者不妨自己假设一下)。开关在A处时,情况类似。
软件消抖主要是通过延时跳过按键抖动的阶段,检测稳定阶段的情况。
下面是代码。
library IEEE; use IEEE.STD_LOGIC_1164.ALL; use IEEE.STD_LOGIC_ARITH.ALL; use IEEE.STD_LOGIC_UNSIGNED.ALL; entity sw_debounce_module is Port ( clk: in STD_LOGIC; rst: in STD_LOGIC; switch : in STD_LOGIC_VECTOR (1 downto 0); led : out STD_LOGIC_VECTOR (1 downto 0)); end sw_debounce_module; architecture Behavioral of sw_debounce_module is signal tmp : STD_LOGIC_VECTOR (1 downto 0); signal cnt : INTEGER range 0 to 1000000; constant max : INTEGER :=500000; begin process(clk,rst,switch(1),switch(0)) begin if(rst = '1') then tmp(1 downto 0)<="00"; cnt <= 0; else if(switch(0)='1')then if(cnt <max and clk='1')then cnt <=cnt+1; elsif(cnt = max) then cnt <= 0; end if; if(switch(0)='1')then tmp(0)<=not tmp(0); end if; end if; if(switch(1)='1')then if(cnt < max and clk='1') then cnt<=cnt+1; elsif(cnt = max) then cnt <= 0; end if; if(switch(1)='1')then tmp(1)<=not tmp(1); end if; end if; end if; end process; led(1 downto 0)<=tmp(1 downto 0); end Behavioral;
由于时钟频率为50MHZ,延时500000周期即为10ms。
为了将程序中的管脚映射到BASYS2开发板上,我们需要建立一个UCF约束文件
下面是约束文件
NET "rst" LOC = "P11"; NET "clk" LOC = "B8"; NET "switch<0>" LOC = "A7"; NET "switch<1>" LOC = "M4"; NET "led<0>" LOC = "G1"; NET "led<1>" LOC = "P4";
依次运行Synthesize -XST,Implement Design和Genetate Programming File。生成可烧录文件。
打开Digilent Adept,有两个选项,第一个为掉电即清除;第二个掉电不清除。选第一个的同时,JP3管脚应选PC模式,选第二个的同时JP3管脚应选ROM模式。
载入程序文件中的.bit文件,点击program即可。