Looping without breaking the code with the Millis function

Has I also use my blog as a reference for myself, I mainly put this there for further reference. I usually use this lines of code to loop without stopping other functions from being executed or to time certain events.

void myFunc()
{
	unsigned long interval = 60 * 1000; // 60 seconds.
	static unsigned long previousMillis;

	if( millis() - previousMillis > interval ) {
		previousMillis = millis();

		/*
			Timed code here.
		*/
	}
}

This function can be called in the main loop() function. Every time it be called, the function checks if the interval of time is reached. If so, the code within the condition is executed. The Millis() function counts the milliseconds since the Arduino is booted.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>