1. 功能描述
这个例子演示了如何防止输入的抖动, 即在很短的时间内两次检查确认按钮确实按下了。没有消除抖动,按一次按钮可以再代码中显示为多次。利用millis ()函数去追踪按钮被按下的时间。
2. 需要硬件
ü Arduino 板子
ü 按钮或者开关
ü 10K欧姆电阻
ü 面包板
3. 电路连接图
链接三条线到Arduino主板。前两条,红色和黑色,链接面包板侧面垂直的两个长行,提供对5v和地的访问。第三条线从数字引脚2链接到按钮的一条退。按钮的另一个相同的针脚链接5v电压。
当按钮打开时(即没有按下),按钮的两条腿之间没有链接,所以,针脚2链接到地(通过下拉电阻),我们读取到一个LOW电平。当按钮关闭(即按下)时,按钮链接它的两条腿,链接针脚2到5v电压,所以,我们读取到一个HIGH电平。
你也可以以相反地方式链接这个电路,通过一个上拉电阻保持输入为HIGH,当按下按钮是变为LOW。如果这样,本程序的动作就会被翻转,LED正常时亮的,当按下按钮时关闭。
如果你没有在数字IO针脚上链接任何东西,LED可能不正确的闪烁。这是因为输入是浮动的-----也就是说,它会随机的返回HIGH或者LOW。这也就是为什么你需要一个上拉或者下拉电阻。
4. 原理图
5. 程序
/*
Debounce
Each time the input pin goes from LOW to HIGH (e.g. because of a push-button press), the
output pin is toggled from LOW to HIGH or HIGH to LOW. There's a minimum delay between
toglles to debounce the circuit (i.e. to ignore noise).
the circuit:
* LED attached from pin 13 to ground
* pushbutton attached to pin 2 from +5v
* 10K resistor attached to pin 2 from ground
* Note: on most Arduinos there is already an LED on the board attached to pin 13
*/
const int ledPin = 13;
const int buttonPin = 2;
int buttonState = 0;
int ledState = HIGH;
int lastButtonState = LOW;
long lastDebounceTime = 0;
long debounceDelay = 10; // milliseconds
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
digitalWrite(ledPin, ledState);
}
void loop()
{
//buttonState = digitalRead(buttonPin);
int reading = digitalRead(buttonPin);
if (reading != lastButtonState)
lastDebounceTime = millis();
if ((millis() - lastDebounceTime) > debounceDelay)
{
if (reading != buttonState)
{
buttonState = reading;
if(buttonState == HIGH)
ledState = !ledState;
}
}
digitalWrite(ledPin, ledState);
lastButtonState = reading;
}
6. 实验照片
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/263104/viewspace-1254573/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/263104/viewspace-1254573/