Using millisec() for a timer

I know there are some background timers running off libraries, and I will further investigate those.
First I would like to make my own timer to execute a task every 6 hours just using the millisec() function.

Some questions.

  1. Does the millisec() value reset/start counting from zero as soon as I power the arduino?
  2. Can I use code to force reset the millisec() value i.e. make it start counting from zero.
  3. What is the correct way to declare the variables to store millisecs, I have seen a number of different ones e.g.
static const unsigned long taskInterval = 21600000; // ms
static unsigned long lastRefreshTime = 0;

Some questions.

  1. Does the millisec() value reset/start counting from zero as soon as I power the arduino?
  2. Can I use code to force reset the millisec() value i.e. make it start counting from zero.
  3. What is the correct way to declare the variables to store millisecs, I have seen a number of different ones e.g.
  1. What is the millisec() function, all I know of is the millis() function that starts as soon as the Arduino is turned on.
  2. No, but you can take the first reading of it, store the value in a variable and take the difference from the current time.
unsigned long prevTime;
const byte buttonPin = 2;

void setup()
{
  Serial.begin(115200);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
  if(digitalRead(buttonPin) == LOW)  prevTime = millis(); 
  
  //If the button is pressed, prevTime is set to the current time (timer resets back to 0), while millis() continues to increase
  Serial.println(millis() - prevTime);
}
  1. That depends if the time is needed to change, like in the example above. By making a variable const is basically telling the compiler that the value in this variable will not change. This is good if you are making a timer that runs at certain intervals.
unsigned long prevTime = 0;
const byte ledPin = 13;
const unsigned long Interval = 1000; // 1 second

void setup()
{
  Serial.begin(115200);
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  if( (millis() - prevTime) >= Interval) // toggle the LED on/off every second
  {
    digitalWrite(ledPin, !digitalRead(ledPin)); // simple toggle
    prevTime += Interval;
  }
}

millis() values should be stored as an unsigned long.

If it's not going to change, you might declare it const, which allows the compiler more room for optimizing.

If you want it scoped within a function (like a local variable), but need it to retain it's value between calls to that function, you would declare it static.

Thanks - the explanations helped.

Check the stopwatch class how to wrap the millis() - Arduino Playground - StopWatchClass

The demo several things at a time illustrates the use of millis() to manage timing.

...R