標(biāo)題: Arduino程序 把按鍵作為開關(guān)的方法 (不用delay) [打印本頁]

作者: dese    時(shí)間: 2022-1-9 10:18
標(biāo)題: Arduino程序 把按鍵作為開關(guān)的方法 (不用delay)
(原創(chuàng))  不用delay, 不阻塞運(yùn)行!

**************************************
int    b2 = 0;       //button state,  default  HIGH
bool b2on = false;
int  wait = 0;      //counter when key is hold

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin1, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin1, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  b2 = digitalRead(buttonPin1);

  if( b2 == LOW )   // pressed,  from HIGH->LOW

  {
    wait++;             // wait for release
  }
  
  if( b2 && wait > 39)              // button return back to HIGH, and  LOW for 39 times

{
    b2on = !b2on;                  // one CLICK  finished!
    wait = 0;                           // reset
  }

  if (b2on) {
    // turn LED on:
    digitalWrite(ledPin1, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin1, LOW);
  }
**************************************


作者: zmc419    時(shí)間: 2022-8-22 18:37
延時(shí)用了wait++,仍然阻塞
作者: zmc419    時(shí)間: 2022-8-22 18:38
用狀態(tài)機(jī)和系統(tǒng)計(jì)數(shù)器才行
作者: dese    時(shí)間: 2022-9-12 08:10
"wait > 39"   這里的 39 根據(jù)你的芯片調(diào)節(jié)到合適的值
作者: Highnose    時(shí)間: 2022-9-12 18:11
用狀態(tài)機(jī)  給力




歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1