Ok, this has been done in different ways before so why again? Hopefully to add some insight as to why one would want to use different delay functions.
You all should be familiar with delay() - it is a simple way of creating a program delay.
pro - simple
con - it is blocking and it uses timer0
Sometimes you come on a library (example RadioHead) which intensively uses internal timers. In some cases this means that not only is the delay() function disrupted, so is millis(). Of course, delay also is blocking which can stop the RadioHead reception in its tracks. What alternatives?
Two Ways
One a non blocking function which allows other operations to continue and does not require the use of interupts. (great as long as timer0 functions are not being modified by something else). This is the use of millis(), a system timer showing elapsed time from processor startup.
millis() based delay;:
nt period = 1000;
unsigned long time_now = 0;
void setup() {
Serial.begin(115200);
}
void loop() {
time_now = millis();
Serial.println("Hello");
while(millis() < time_now + period){
// add the code you want to keep running here
//wait approx. [period] ms
}
// handle whatever you want to handle after the pause here, than start allover again
}
** OR BETTER YET :**
** try this tutorial**
Blink without Delay - Arduino Tutorial
TWO - a blocking delay, but one that does NOT use timers (timer0, timer1, or timer2) and is able to work with libraries which have a lot of timing issues or which corrupt millis() or timer0 counts.
delayMicroseconds
here is a code snippet for a function to give a delay specified in seconds. There is no particular limitation on this although if you have really long delays and do NOT have to worry about using timers, I would recommend interupt timers and using ISRs.
void ntDelay(byte t){ // non timer delay in seconds
for (byte i = 0; i < t*1000; i++) {
delayMicroseconds(1000);
}
}
So, add these two delays to your programing tool kit and between them, delay() you should almost never have to use interupt timers.
enjoy