...Or, even better, if you want to service something every second you can check the value of millis to see if a second has elapsed since the last service. http://www.arduino.cc/en/Reference/Millis
One could always use one of these libraries: (Both uses millis(), but hides the arithmetic from the client code)
This enables you to use the timer for something else, if you want. You do not really need timer resolution for events that occur every second. Both of these will work.
#include <Metro.h> //Include Metro library
#define LED 13 // Define the led's pin
//Create a variable to hold theled's current state
int state = HIGH;
// Instantiate a metro object and set the interval to 250 milliseconds (0.25 seconds).
Metro ledMetro = Metro(250);
void setup()
{
pinMode(LED,OUTPUT);
digitalWrite(LED,state);
}
void loop()
{
if (ledMetro.check() == 1) { // check if the metro has passed it's interval .
if (state==HIGH) {
state=LOW;
ledMetro.interval(250); // if the pin is HIGH, set the interval to 0.25 seconds.
}
else {
ledMetro.interval(1000); // if the pin is LOW, set the interval to 1 second.
state=HIGH;
}
digitalWrite(LED,state);
}
}
#include <TimedAction.h>
//this initializes a TimedAction class that will change the state of an LED every second.
TimedAction timedAction = TimedAction(1000,blink);
//pin / state variables
const byte ledPin = 13;
boolean ledState = false;
void setup(){
pinMode(ledPin,OUTPUT);
digitalWrite(ledPin,ledState);
}
void loop(){
timedAction.check();
}
void blink(){
ledState ? ledState=false : ledState=true;
digitalWrite(ledPin,ledState);
}
![]()