Timers and delays

Hello guys, so i'm working on something that requires some timers, basically a limit switch is activated, once is activated:

  • it starts a count in seconds
  • after x amount of seconds the limitswitch has been activated i want it to activate
    an LED for an X amount of seconds.

so that's a timer within a timer, so far i'm using:

  • a delay every 1 sec to read the limit switch more accurately since its reading
    when is HIGH or LOW,
    -every time the limit switch is HIGH it adds 1 second to an "unsigned long variable"
    -when the limit switch is "LOW" it resets the timer to 0

so my question is how can i run a timer for an x amount of seconds without using a delay function, i've look into the "millis" command but i can't get a grip of it yet

millis() returns an unsigned long value of milliseconds since startup.

It rolls over every 49.7-some days but by using unsigned math that's only a problem if you want to get the difference between two times more than 49.7 days apart.

Using variables and millis() you can time many things. The big trick is to always work with the difference between two times rather than use more than or less than just one time.

time now - time before = difference between now and before, always

if ( timeWait > 0UL ) // for when I want to stop or start a time check, wait time becomes a flag
{
if ( millis() - timeStart >= timeWait )
{
// wait is over, do what is needed
timeStart += timeWait; // do this if you want to run another interval
timeWait = 0UL; // or do this to NOT run another interval
}
}

There is a really good, simple, commonsense lesson on the subject at the first link below.

Look at how millis() is used in the demo several things at a time.

You need to record millis() when the limit switch is pressed - eg. limitSwitchPressedMillis = millis()

then use a test - something like

if (millis() - limitSwitchPressedMillis >= waitingTimeMillis) {

    // start another timer
    ledStartMillis = millis();
    digitalWrite(ledPin, HIGH);
}

if (millis() - ledStartMillis >= ledTimeMillis) {
   digitalWrite(ledPin, LOW);
}

...R

Thanks for the help and for the link, it was helpful for sure!