Home Automation blog

Skip to Content

Arduino multi-timer function

Posted by Chris

Date posted:

I wrote a reusable non-blocking function for Arduino projects to easily handle different timers with different intervals.

This quick example repeatedly prints when each timer has reached their respective intervals. Showing that two or more timers can simultaneously run at the same time without effecting each other, using the same getTimer function.

// First timer ~ 3 second interval
unsigned long timer_a = 0;
int interval_a = 3000;

// Second timer ~ 10 second interval
unsigned long timer_b = 0;
int interval_b = 10000;

void setup()

void loop()
	// If timer A's interval is reached, print message
	if (getTimer(timer_a, interval_a))
	// If timer B's interval is reached, print message
	if (getTimer(timer_b, interval_b))
		Serial.println("  B!");

 * Determine if given timer has reached given interval
 * @param unsigned long tmr The current timer
 * @param unsigned long interval Length of time to run timer
 * @return bool True when timer is complete, has reached interval.
 * @return bool False when timer is incomplete, hasn't reached interval.
bool getTimer(unsigned long &tmr, unsigned long interval)
	// Set initial value
	if (tmr < 1)
		tmr = millis();

	// Determine difference of our timer against millis()
	if (millis() - tmr >= interval)
		// Complete! Reset timer
		tmr = 0;
		return true;

	// Interval not reached
	return false;

View similar posts categorised as: Arduino