## 按鍵去抖
> 由于物理性質和機械特性等原因,矩陣按鍵經常在按下后的一小段時間產生不定狀態。這很可能被程序誤認為在短時間內進行了多次按鍵操作。本例向你展示如何進行**按鍵去抖**:通過在一小段間隔時間后再次讀取按鍵狀態的方式,來確保按鍵確實是完全被按下了(簡單來說就是”濾去”發生按鍵抖動的時間)。
當**按鍵抖動**發生的時候會產生不可預期的效果。本例使用**millis()**函數來算得按鍵按下后經過的時間,以避免按鍵抖動造成的影響。
### 所需硬件
Arduino板或Genuino板?
自鎖按鈕或開關?
10kΩ電阻?
面包板跳線?
面包板
### 電路

### 原理圖

### 代碼
下面的例程借鑒了Limor Fried的代碼,但是代碼邏輯與她的相反。在她的范例中,開關閉合Arduino讀出的是LOW,斷開讀出的是HIGH。而本例中開關閉合Arduino讀出的是HIGH,斷開讀出的是LOW。
### 例程代碼
~~~
/*
按鍵去抖
每當輸入引腳發生高低電平的變化時(比如由于矩陣按鍵被按下了),或當輸出引腳發生高低電平的變化時,程序就應該暫停一小段時間來避免這個抖動的干擾(或者說避免這種電子噪聲的干擾)。
電路搭建:
* LED連接13號引腳和GND
* 矩陣按鍵連接2號引腳和+5V
* 10kΩ電阻連接2號引腳和GND
* 小貼士: 大多數Arduino板在13號引腳已經有板載LED,所以你一般不用附加LED來完成本例。
代碼是公開的
*/
// 常量,用來定義引腳號碼
const int buttonPin = 2; // 連接矩陣按鍵的引腳
const int ledPin = 13; // LED引腳
// 變量的聲明與定義:
int ledState = HIGH; // 記錄LED的狀態
int buttonState; // 記錄按鍵的狀態
int lastButtonState = LOW; // 上一次按鍵的狀態
// 以下代碼以long類型聲明,因為時間值以毫秒為單位(用整型會很快溢出)
long lastDebounceTime = 0; // 按鍵最后一次被觸發
long debounceDelay = 50; // 為了濾去抖動暫停的時間,如果發現輸出不正常增加這個值
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
// 設置LED初始狀態
digitalWrite(ledPin, ledState);
}
void loop() {
// 讀取按鍵狀態并存儲到變量中:
int reading = digitalRead(buttonPin);
// 檢查下按鍵狀態是否改變(換句話說,輸入是否是從LOW到HIGH)。
// 檢查是否距離上一次按下的時間已經足夠濾去按鍵抖動:
// 如果按鍵狀態和上次不同:
if (reading != lastButtonState) {
// 記錄初始時間
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// 離初始時間已經過了按鍵抖動出現的時間,因此當前的按鍵狀態是穩定狀態:
// 如果按鍵狀態改變了:
if (reading != buttonState) {
buttonState = reading;
// 只有當穩定的按鍵狀態時HIGH時才打開LED。
if (buttonState == HIGH) {
ledState = !ledState;
}
}
}
// 設置LED:
digitalWrite(ledPin, ledState);
// 保存處理結果:
lastButtonState = reading;
}
~~~
## 相關資料
[pinMode()](http://www.arduino.cc/en/Reference/PinMode)?
[digitalWrite()](http://www.arduino.cc/en/Reference/DigitalWrite)?
[digitalRead()](http://www.arduino.cc/en/Reference/DigitalRead)?
[if()](http://www.arduino.cc/en/Reference/If)?
[millis()](http://www.arduino.cc/en/Reference/Millis)?
- 說明
- 系統示例文件目錄結構及說明
- 01.Basics
- AnalogReadSerial
- BareMinimum
- Blink
- DigitalReadSerial
- Fade
- ReadAnalogVoltage
- 02.Digital
- BlinkWithoutDelay
- Button
- Debounce
- DigitalInputPullup
- StateChangeDetection
- toneKeyboard
- toneMelody
- toneMultiple
- tonePitchFollower
- 03.Analog
- AnalogInOutSerial
- AnalogInput
- AnalogWriteMega
- Calibration
- Fading
- Smoothing
- 04.Communication
- ASCIITable
- Dimmer
- Graph
- Midi
- MultiSerial
- PhysicalPixel
- ReadASCIIString
- SerialCallResponse
- SerialCallResponseASCII
- SerialEvent
- SerialPassthrough
- VirtualColorMixer
- 05.Control
- Arrays
- ForLoopIteration
- IfStatementConditional
- switchCase
- switchCase2
- WhileStatementConditional
- 06.Sensors
- ADXL3xx
- Knock
- Memsic2125
- Ping
- 07.Display
- barGraph
- RowColumnScanning
- 08.Strings
- CharacterAnalysis
- StringAdditionOperator
- StringAppendOperator
- StringCaseChanges
- StringCharacters
- StringComparisonOperators
- StringConstructors
- StringIndexOf
- StringLength
- StringLengthTrim
- StringReplace
- StringStartsWithEndsWith
- StringSubstring
- StringToInt
- 09.USB
- Keyboard
- KeyboardLogout
- KeyboardMessage
- KeyboardReprogram
- KeyboardSerial
- KeyboardAndMouseControl
- Mouse
- ButtonMouseControl
- JoystickMouseControl
- 10.StarterKit_BasicKit (與特定硬件相關,暫無)
- p02_SpaceshipInterface
- p03_LoveOMeter
- p04_ColorMixingLamp
- p05_ServoMoodIndicator
- p06_LightTheremin
- p07_Keyboard
- p08_DigitalHourglass
- p09_MotorizedPinwheel
- p10_Zoetrope
- p11_CrystalBall
- p12_KnockLock
- p13_TouchSensorLamp
- p14_TweakTheArduinoLogo
- p15_HackingButtons
- 11.ArduinoISP(暫無)
- ArduinoISP