How to Create Timer in Arduino: Simple Guide with Example
To create a timer in Arduino, use the
millis() function which returns the number of milliseconds since the board started. By saving the start time and checking the elapsed time repeatedly, you can run code after a set delay without stopping the program.Syntax
The basic syntax to create a timer in Arduino uses the millis() function:
unsigned long startTime = millis();- saves the current time in milliseconds.if (millis() - startTime >= interval)- checks if the desired time interval has passed.- Run your code inside the
ifblock to execute after the timer expires.
arduino
unsigned long startTime = millis(); unsigned long interval = 1000; // 1 second void loop() { if (millis() - startTime >= interval) { // Code to run every 1 second startTime = millis(); // reset timer } }
Example
This example blinks the built-in LED every 1 second using a timer created with millis(). It does not block other code from running.
arduino
const int ledPin = LED_BUILTIN; unsigned long previousMillis = 0; const unsigned long interval = 1000; // 1 second void setup() { pinMode(ledPin, OUTPUT); } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; digitalWrite(ledPin, !digitalRead(ledPin)); // toggle LED } }
Output
The built-in LED on the Arduino board blinks on and off every 1 second.
Common Pitfalls
Common mistakes when creating timers in Arduino include:
- Using
delay()which blocks the program and stops other code from running. - Not resetting the start time after the interval, causing the timer to trigger only once.
- Using
intinstead ofunsigned longfor time variables, which can cause overflow errors.
Always use unsigned long for time values and reset the timer inside the if block.
arduino
/* Wrong way: Using delay blocks all code */ void loop() { digitalWrite(LED_BUILTIN, HIGH); delay(1000); // blocks program digitalWrite(LED_BUILTIN, LOW); delay(1000); } /* Right way: Using millis() timer */ unsigned long previousMillis = 0; const unsigned long interval = 1000; void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); } }
Quick Reference
Tips for creating timers in Arduino:
- Use
millis()for non-blocking timers. - Store start time in
unsigned longvariables. - Check elapsed time by subtracting start time from current
millis(). - Reset start time after timer triggers to repeat.
- Avoid
delay()for multitasking.
Key Takeaways
Use millis() to create non-blocking timers in Arduino.
Always store time values in unsigned long variables to avoid overflow.
Reset the timer start time after each interval to repeat the timer.
Avoid delay() to keep your program responsive.
Check elapsed time by subtracting start time from current millis().