Inverter switch while delay

Hi everyone,

I have a membrane keyboard connected to my Arduino nano and I want to control a relay with it. So far, this work fine, except one thing I am not sure how to solve it.

Key 1 should always switch the relay in the opposite state as it currently is. This of course is in conflict with the 21 sec delay of Key 2 which should switch the relay on for n (in this case 21) seconds. If Key 1 is pressed within this time the rely should be switched of.

Does anybody has an idea what else I can used rather than delay which works in my case?

Thanks, raivan!

My code:

void loop()
{
  
  char keypressed = myKeypad.getKey();
  if (keypressed != NO_KEY) {
    Serial.print("K ");
    Serial.write(keypressed);
    Serial.println("");
    Serial.flush();
  }
    
  if (keypressed == '1') {
      if (digitalRead(relayPin) == LOW) {
        digitalWrite(relayPin, HIGH); 
      }
      else {
        digitalWrite(relayPin, LOW); 
      }
  }

  if (keypressed == '2') {
    digitalWrite(relayPin, HIGH); 
    delay(21000);
    digitalWrite(relayPin, LOW); 
  }
        
}

You have to keep the loop running if you want to respond to other things. See the "Blink Without Delay" example for an example of how to use millis to time something. Basically, you record the time from millis when some event happens, like a user pressing the 2, and on each pass of loop do all your other things and check to see how long it has been since then by reading millis again and subtracting. Instead of thinking "wait until 21 seconds have passed" think "keep checking to see if 21 seconds have passed".

Hi Delta_G,

thank you for the hint. Do you have an idea how to implement millis with my if (keypressed == '2') condition? I've just tried to put the code from the "Blink Without Delay" example after my if condition. This had the effect that I had to push Key 2 a second time after the interval to again switch off the rely.

Thanks!

raivan:
Hi Delta_G,

thank you for the hint. Do you have an idea how to implement millis with my if (keypressed == '2') condition? I've just tried to put the code from the "Blink Without Delay" example after my if condition. This had the effect that I had to push Key 2 a second time after the interval to again switch off the rely.

Thanks!

Don't just stick the code in. That's not how code works. Study it and understand how it works. When you do, it will be really obvious how to do it. I explained it pretty well in the post above.

Note that you may need additional logic. Probably a boolean that tracks whether the timer is running or not.

The demo Several Things at a Time is an extended example of BWoD and illustrates the use of millis() to manage timing.

It may help with your understanding or provide a base from which to develop your program.

Planning and Implementing a Program also uses that technique.

...R