Search code examples
arduinodelay

delay prevent keypad input till it ednds


I am trying to set the delay of a blinking led using 4*4 keypad, but when the delay is large u have to wait for it to end so u can enter another num using the keypad. so how can I get the input of the keypad while the delay is on ?

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);
}

Solution

  • You can use the millis() function to create a blink without delay function and call it after a keypress. Also, there is a good example in here.

    So you can rewrite your code with something like this:

    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();
    }