I’ve noticed that a lot of Arduino users complain of the millis() function and the fact that it overflows after 49.7 days (2^32 ms) and the problems that the library generates into the projects that are always on and use sketches that are written without considering this. So I decided to use the knowledge on the microcontroller’s timers that I gained writing the swRTC library and try to create a new library that I just named secTimer.
This timer only uses an internal timer of the Arduino (or the microcontroller fo your project, in standalone circuits) to manage a simple seconds counter. So the minimum interval that can manage is the SECOND: it can not manage shorter intervals. This resolution is good enough for operations that have to be executed with longer intervals (i.e. driving LEDs or lights for day/night effects or reading a sensor).
What’s the advantage of secTimer over millis()? Millis() overflows after 49.7 days, instead secTimer will overflow after more than 136 years! This means that your device will cease to work a lot of time before secTimer will restart from 0!
To use the library, just unpack it into your libraries’ folder. I suggest to create a folder named /libraries inside the /sketchbook folder (/home/utente/sketchbook for Linux, Documents\Arduino for Windows). After installation, to use the library you just have to include it into your project, create a new istance of it, start the counter and then read the seconds at your own need. There’s an explanatory example that shows the use of the secTimer library.
I also added the start and stop functions of the counter because the library uses an hardware timer and you could have the necessity to use that timer simultaneously for other works for a short period so you can stop the counter, do your tasks and then restart it.
The size impact of the library is little, about 350 bytes on my Linux box: BlinkWithoutDelay creates a sketch that is 992 bytes is size while timerLed creates a sketch that is 1342 bytes.
The library supports a wide variety of microcontrollers, from Atmega328 (Arduino UNO) to Atmega32U4 (Arduino Leonardo), from Atmega2560 (Arduino MEGA) to Atmega644/1284 (the complete list is included in the readme.txt file), included all the MCUs supported by the Tiny core (Attiny84/85/2313 ecc.).
The library is released under the therms of the GNU GPL 3.0 license or newer.
I updated the library choosing the new name secTimer, to avoid confusion with another library named Time. More over, inside the package you will find a file to substitute a core’s file of the Arduino 0022 in case you would use this version of the IDE: using this mod you can have a new function called delaySeconds that relies on the same algorithm used by Arduino to computer millis(), so you don’t loose any additional timer. This mod will only work with the Arduino core.