Changing motor run time based on selector switch.

I have an application where I need to run a motor for certain on/off times based on user input. I would like to use a 12 position rotary switch and have set run times based on the switch position. My problem is that I need to be able to cancel a previous run time if someone changes the position of the switch before the previous set time has expired.

For example: Set time 1:

On for 1 minute off for 8 hours.

So if someone turns the switch to a different position during the 8 hour off countdown I currently have to wait untill the 8 hours is over before the new setting is run in the loop.

Is there a way to solve this? Keep in mind I have 12 different modes with differing times.

thanks!

So constantly check in loop() if the switch has changed position. If it has, update the timer. Leo..

This could get you started (untested).
Leo…

byte pos; // holds switch position (1-12)
byte prevPos; // previous switch position

void setup() {
  for (byte i = 2; i <= 13; i++) pinMode(i, INPUT_PULLUP); // switch 1-12 to pin 2-13, common to ground
}

void loop() {
  for (byte i = 2; i <= 13; i++) if (!digitalRead(i)) pos = i - 1; // update switch position
  if (pos != prevPos) {
    switch (pos) { // act on position change
      case 1:
        // action for switch position 1
        break;
      case 2:
        // for pos 2
        break;
        //etc.
    }
  }
  prevPos = pos; // update
}

Thanks Leo,

I will attempt this and let you know how it goes!

Hi PechanWY, I suspect you are using the delay() function in your timing code. Learn how not to use delay(), but still be able to time events.

Have a look at how millis() is used to manage timing without blocking in Several Things at a Time.

And see Using millis() for timing. A beginners guide if you need more explanation.

…R