VHDL代码心得3-按键消抖

消抖的代码部分可以说是非常简单了,主要是理解消抖原理。按键在按下的时候,看上去是只按了一次,其实按键刚按下时抖动了很多次,这是机械特性,无法避免。消抖的代码思想是内置一个计数器,计数器每当检测到抖动时复位,只有当计数器计数到某个数值(该数值对应时间大于抖动周期)时,才把按键输入接入到消抖模块的输出。至于如何检测抖动,则是通过两个内部信号,在一个进程写按键输入赋值给信号1,信号1赋值给信号2两个语句,由于进程内部赋值不是立即执行的,两个赋值语句有一个时钟周期的时间差。对信号1与信号2取异或作为复位信号,平时复位信号为0,仅当按键输入变化时(即按下,松手或抖动)复位信号为1,这样就实现了抖动的检测。事实上,把数值改一下可以将功能由消抖变为检测长按,此处不再赘述。

library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
entity key_debounce is
port( clk,key: in std_logic;
		key_out: out std_logic);
end key_debounce;
architecture behav of key_debounce is
signal counter:integer range 0 to 500;
signal df_1,df_2,df,rst_n:std_logic;
signal temp:std_logic:='1';
constant timer:integer:=5000;
begin


process(clk)
begin
if clk'event and clk='1' then
df_1<=key;
df_2<=df_1;
end if;
df<=df_1 xor df_2;
rst_n<=df;
end process;

process(clk,rst_n)
begin
if rst_n='1' then
counter<=0;
elsif clk'event and clk='1' then
counter<=counter+1;
if counter=timer then  
counter<=0;
temp<=key;
end if;
end if;
end process;
key_out<=temp;
end behav;


补充:实验证明timer设置成500000,即消除0.1s以内的抖动较为合理。
补充:仔细看了一下之前的代码,其实是有问题的,仅当counter=timer时读取,则按键按下之后需要等待timer/50M才能读取按键。以下是更正后的。

library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
entity key_debounce is
port( clk,key: in std_logic;
		key_out: out std_logic);
end key_debounce;
architecture behav of key_debounce is
signal counter:integer range 0 to 50000000;
signal df_1,df_2,df,rst_n:std_logic;
constant timer:integer:=5000;
begin


process(clk)
begin
if clk'event and clk='1' then
df_1<=key;
df_2<=df_1;
end if;
df<=df_1 xor df_2;
rst_n<=df;
end process;

process(clk,rst_n)
begin
if rst_n='1' then
counter<=0;
elsif clk'event and clk='1' then
counter<=counter+1;
if counter=50000000 then  
counter<=0;
end if;
if counter>=timer then
key_out<=key;
end if;
end if;
end process;
end behav;

  • 8
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值