Im not good in arduino, but I have project that control motor using limit switch.

The rule is:

  1. When switch OFF, motor ON

  2. When switch ON, motor OFF for 1 hour (i dont want use delay because cannot multitasking so it will be stopped another program which have to running in the same time)

  3. After 1 hour, motor ON (although switch state still ON)

What type of timer I have to use? And how the code? Thanks. Sorry if i dont have any codes.

  • You can do a 1 hour delay with 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

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){
    // switch off the motor here
    timestamp = millis();
  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.

  • you only need to debounce the switch OFF, when the motor starts up – jsotola Apr 2 '18 at 19:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.