實現按鍵控制LED亮滅。按下點亮,再次按下熄滅。css
int ButtonState;
int ButtonLastState;
int ButtonCounter;
void setup() {
// put your setup code here, to run once:
pinMode(13,OUTPUT);
pinMode(11,INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
ButtonState = digitalRead(11);
if(ButtonState != ButtonLastState)
{
if(ButtonState)
{
Serial.println("on");
ButtonCounter++;
}
else
{
Serial.println("off");
}
delay(100);
}
ButtonLastState = ButtonState;
if(ButtonCounter%2)
{
//Serial.println(ButtonCounter);
digitalWrite(13,1);
}
else
{
digitalWrite(13,0);
}
}
ButtonState
和ButtonLastState
兩個標誌位來判斷電平狀況,經過這兩個標誌位實現了降低沿和上升沿進入第一個判斷語句,即if(ButtonLastState != ButtonState)
,只不過降低沿和上升沿所處理的操做不一樣,降低沿不作處理,僅打印一條語句,上升沿時候則表明按鍵被按下而且已經放開了,則對按鍵次數進行加一。