## 按鈕狀態檢測
> 當你使用按鈕時,有時需要知道按鈕被按下了多少次,為了這個目的,你需要知道當按鈕按下時,狀態的改變,并且能夠記錄統計次數,這就是狀態檢測或邊緣檢測。
> 在這個示例中,我們要學會如何檢測這種改變,并且把信息發送到串口監視器,并且改變led的亮暗。
### 所需硬件
* Arduino
* 按鍵
* 10k 電阻
* 導線
* 面包板
### 電路

按鈕的一端通過10K下拉電阻接地,并且連接到數字引腳I/O口2,來讀取按鈕的狀態,另外一端連接到5V
當按鈕沒有被按下的時候,兩個引腳之間是斷開的,這時候我們的數字引腳通過下拉電阻接地,讀出數值LOW,
當按鈕按下時,按鈕的兩個引腳被連接上了,引腳連接到了電壓,所以我們讀出HIGH,(因為電路中電阻的阻礙作用,所以這個引腳是連接到了+5V)
### 原理圖
[](https://www.arduino.cc/en/uploads/Tutorial/button_sch.png)
### 代碼
這個程序不斷的讀取按鈕的狀態,并且比較當前和以前的按鈕狀態,如果狀態發生了改變,那么按鈕被按下,如果按鈕按下的次數是四的倍數的時候,改變13腳led的亮滅
/*
? State change detection (edge detection)
? Often, you don't need to know the state of a digital input all the time, but
? you just need to know when the input changes from one state to another.
? For example, you want to know when a button goes from OFF to ON. This is called
? state change detection, or edge detection.
? This example shows how to detect when a button or button changes from off to on
? and on to off.
*/
// this constant won't change:
const?int??buttonPin?=?2;?? ?// the pin that the pushbutton is attached to
const?int?ledPin?=?13;?? ? ??// the pin that the LED is attached to
// 定義變量:
int?buttonPushCounter?=?0;???// 按鈕按下次數計數器,
int?buttonState?=?0;?? ? ? ??// 當前按鈕的狀態,
int?lastButtonState?=?0;?? ??// 上一次按鈕的狀態,
void?setup()?{
??//初始化按鈕作為輸入,
??pinMode(buttonPin,?INPUT);
??//初始化led作為輸出,:
??pinMode(ledPin,?OUTPUT);
??// 初始化串口,:
??Serial.begin(9600);
}
void?loop()?{
??// 讀取按鈕輸入引腳,
? buttonState?=?digitalRead(buttonPin);
??// 比較按鈕的當前狀態和以前的狀態,
??if?(buttonState?!=?lastButtonState)?{
? ??// 如果按鈕狀態發生了改變,增加計數
? ??if?(buttonState?==?HIGH)?{
? ? ??// if the current state is HIGH then the button went from off to on:
? ? ? buttonPushCounter++;
? ? ??Serial.println("on");
? ? ??Serial.print("number of button pushes: ");
? ? ??Serial.println(buttonPushCounter);
? ??}?else?{
? ? ??// if the current state is LOW then the button went from on to off:
? ? ??Serial.println("off");
? ??}
? ??// Delay a little bit to avoid bouncing
? ??delay(50);
??}
??// 保存當前的狀態,作為下一個循環使用,
? lastButtonState?=?buttonState;
??// 如果按鈕按下的次數是四的倍數,點亮led,
??if?(buttonPushCounter?%?4?==?0)?{
? ??digitalWrite(ledPin,?HIGH);
??}?else?{
? ??digitalWrite(ledPin,?LOW);
??}
}
### 相關資料:
* [pinMode](https://www.arduino.cc/en/Reference/PinMode)()
* [digitalWrite](https://www.arduino.cc/en/Reference/DigitalWrite)()
* [digitalRead](https://www.arduino.cc/en/Reference/DigitalRead)()
* [millis](https://www.arduino.cc/en/Reference/Millis)()
* [if](https://www.arduino.cc/en/Reference/If)
- 說明
- 系統示例文件目錄結構及說明
- 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