首页 > 解决方案 > 延迟防止键盘输入直到它结束

问题描述

我正在尝试使用 4*4 键盘设置闪烁 LED 的延迟,但是当延迟很大时,您必须等待它结束,以便您可以使用键盘输入另一个数字。那么如何在延迟开启时获得键盘的输入?

void loop() {
  char key = keypad.getKey();

  if (key != NO_KEY) {
    if (key != 'A' && key != 'B' && key != 'C' && key != 'D' && key != '*' && key != '#') {

      Serial.print(key - 48);
      value = value + key;
      num = value.toInt();
    }
  }

  if (key == 'D'){
    wait = num;
    value = "";
  }

  digitalWrite(led, 1);
  delay(wait);
  digitalWrite(led, 0);
  delay(wait);
}

标签: arduinodelay

解决方案


您可以使用该millis()函数创建无延迟闪烁功能,并在按键后调用它。此外,这里有一个很好的例子

所以你可以用这样的东西重写你的代码:

int wait;
int ledState = LOW; // ledState used to set the LED

unsigned long currentMillis, previousMillis;

void blink_without_delay()
{
    currentMillis = millis();
    if (currentMillis - previousMillis >= wait)
    {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW)
        {
            ledState = HIGH;
        }
        else
        {
            ledState = LOW;
        }

        // set the LED with the ledState of the variable:
        digitalWrite(ledPin, ledState);
    }
}

void setup()
{
    // Do your setup in here
}

void loop()
{
    char key = keypad.getKey();

    if (key != NO_KEY)
    {
        if (key != 'A' && key != 'B' && key != 'C' && key != 'D' && key != '*' && key != '#')
        {

            Serial.print(key - 48);
            value = value + key;
            num = value.toInt();
        }
    }

    if (key == 'D')
    {
        wait = num;
        value = "";
    }

    blink_without_delay();
}

推荐阅读