【【計算機(jī)大俠】Arduino教程:按鍵消抖】https://toutiao.com/group/6703127408653894152/?app=explore_article×tamp=1560724254&req_id=201906170630530101520170937899F97&group_id=6703127408653894152&tt_from=copy_link&utm_source=copy_link&utm_medium=toutiao_ios&utm_campaign=client_share 防抖當(dāng)按下時,按鍵經(jīng)常產(chǎn)生錯誤的開/關(guān)變遷,這是機(jī)械物理的問題:這些變遷可能被讀取為在短時間內(nèi)多次按下,從而使程序變笨。這個例子示范了怎樣使一個輸入防抖,這意味著在一個短時間內(nèi)檢查兩次來確保這個按鍵是確實被按下了。如果沒有防抖,按一次這個按鍵可能會引起不可預(yù)測的結(jié)果。這個程序利用millis()函數(shù)來保持按下的時間間隔。 按鍵消抖原理當(dāng)按下時,按鍵經(jīng)常產(chǎn)生錯誤的開/關(guān)變化,這是機(jī)械物理的問題:這些變化可能被讀取為在短時間內(nèi)多次按下,從而使程序變笨。這個例子示范了怎樣使一個輸入防抖,這意味著在一個短時間內(nèi)檢查兩次來確保這個按鍵是確實被按下了。如果沒有防抖,按一次這個按鍵可能會引起不可預(yù)測的結(jié)果。這個程序利用millis()函數(shù)來保持按下的時間間隔。 硬件要求
代碼 例子里,當(dāng)閉合時開關(guān)為低電平,而斷開時開關(guān)未高電平。這里當(dāng)按下開關(guān)時為高電平,沒有按下時為低電平。 // constants won't change. They're used here to// set pin numbers:const int buttonPin = 2; // the number of the pushbutton pinconst int ledPin = 13; // the number of the LED pin// Variables will change:int ledState = HIGH; // the current state of the output pinint buttonState; // the current reading from the input pinint lastButtonState = LOW; // the previous reading from the input pin// the following variables are long's because the time, measured in miliseconds,// will quickly become a bigger number than can be stored in an int.long lastDebounceTime = 0; // the last time the output pin was toggledlong debounceDelay = 50; // the debounce time; increase if the output flickersvoid setup() { pinMode(buttonPin, INPUT); pinMode(ledPin, OUTPUT); // set initial LED state digitalWrite(ledPin, ledState);}void loop() { // read the state of the switch into a local variable: int reading = digitalRead(buttonPin); // check to see if you just pressed the button // (i.e. the input went from LOW to HIGH), and you've waited // long enough since the last press to ignore any noise: // If the switch changed, due to noise or pressing: if (reading != lastButtonState) { // reset the debouncing timer lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { // whatever the reading is at, it's been there for longer // than the debounce delay, so take it as the actual current state: // if the button state has changed: if (reading != buttonState) { buttonState = reading; // only toggle the LED if the new button state is HIGH if (buttonState == HIGH) { ledState = !ledState; } } } // set the LED: digitalWrite(ledPin, ledState); // save the reading. Next time through the loop, // it'll be the lastButtonState: lastButtonState = reading;} |
|