2

I'm experimenting with a Nano, and trying to trigger an action around twice a day. I'm aware that it's not super accurate, but I don't really mind, as long as it's in the ballpark.

I've tried using the SimpleTimer library but I'm running into an issue because it takes milliseconds as an int, and 12 hours is 43200000 (larger than 32,767 max). Is there another library, or another technique I can use for this?

3
  • 2
    On the page you linked it takes a long as an argument, not an int: int setInterval(long d, timer_callback f).
    – Nick Gammon
    Dec 8, 2016 at 20:09
  • @NickGammon has it; there is no such limitation on the interval argument to setInterval() as "it takes milliseconds as an int". It takes a signed long, though it treats it internally as unsigned long, thus the max interval is over 49 days. Mark's answer will work, too, but is not actually necessary.
    – JRobert
    Dec 9, 2016 at 14:41
  • I better make it an actual answer then. :)
    – Nick Gammon
    Dec 9, 2016 at 20:55

3 Answers 3

6

Set the timer for every hour, which is within the limit. In your action, keep a static int, initialized to zero, which you increment each time. When it ==12, do the thing you want to do and reset your int back to zero.

1
  • dang that's simple and smart
    – user379468
    Dec 8, 2016 at 19:54
5

I'm running into an issue because it takes milliseconds as an int ...

No it doesn't. Look at the function prototype:


int setInterval(long d, timer_callback f);

Call function f every d milliseconds. The callback function must be declared as void f().


The interval d is a long. The int you see is the return value from the function, not the interval.

1

You have 2 other options to the setInterval() function:

  • delay() (blocking)
  • millis() (non-blocking)

Both of these functions deal with an unsigned long which has 32 bits = (2^32)-1 = 4,294,967,295. Doing the sums (and considering that both are in milliseconds), this will last for 49 days and 17 hours.

1 second = 1000 milliseconds
1 minute = 60 seconds
1 hour = 60 minutes
12 hours = 12 * 60 * 60 * 1000 = 43,200,000

delay(x) will delay for x number of milliseconds. The delay function is blocking, meaning that while it is running/delaying you can't do any other task. The code would be:

delay(43200000);

millis() on the other hand is non-blocking and returns the number of milliseconds since power-up. This can be implemented with the following code:

#define TWELVE_HRS 43200000UL
unsigned long startTime;

setup()
{
  startTime = millis();
}

loop()
{
  if (millis() - startTime > TWELVE_HRS)
  {
    // Put your code that runs every 12 hours here

    startTime = millis();
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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