There is no need to do a complex thing like using extra timers for this. You can use non-blocking code with the millis()
function, like in the BlinkWithoutDelay
example of the Arduino IDE (You should really try it and understand how it works). The millis()
function returns the number of milliseconds since the Arduino has powered up and it will overflow after about 50 days (and with the code from the mentioned example this wouldn't be a problem either).
Basically you save a timestamp of the last event and check, if it is time to do something. For your case I would add a boolean, indicating, that the motor should be off and that the state of the switch doesn't matter anymore. Then (I assume that you want to disable the motor again by switching to OFF and ON again) you would have to reset this variable, when the switch goes to OFF state again. Something like this:
boolean state=true; // on by default
unsigned long timestamp=0;
void loop(){
if(switch_on() && state){
state=false;
// switch off the motor here
timestamp = millis();
}
if(switch_off()){
state=true;
}
if(!state && millis()-timestamp > INTERVAL){
//switch on the motor here
}
}
Be sure to have a good code for checking the switch state, since most mechanical buttons need debounce code. In the above code I replaced this with simple functions to illustrate the timing functionality.
millis()
(though it's not 100% accurate). If the time now, minus the time when the switch got pressed, is more than one hour then turn on the motor. – Majenko♦ Apr 2 '18 at 12:12