This chapter explores the different time-tracking functions in Arduino, including millis(), micros(), delay(), and delayMicroseconds(). These functions allow you to measure time, create delays, and manage events based on elapsed time.
Syntax Table: Arduino Timers
Topic | Syntax | Simple Example |
millis() | millis(); | unsigned long currentMillis = millis(); |
micros() | micros(); | unsigned long currentMicros = micros(); |
delay() | delay(milliseconds); | delay(1000); (1-second delay) |
delayMicroseconds() | delayMicroseconds(microseconds); | delayMicroseconds(500); (500-microsecond delay) |
millis() – Return Elapsed Time in Milliseconds in Arduino
millis() is an Arduino function that returns the number of milliseconds that have passed since the program started running. This function is useful for tracking time, creating delays without stopping the entire program, and handling timing tasks in Arduino projects. Unlike the delay() function, millis() allows the Arduino to continue executing other tasks while keeping track of the elapsed time.
Use purpose
The millis() function is used for:
- Measuring elapsed time: You can track how much time has passed since the program started or between events.
- Non-blocking delays: Unlike delay(), millis() allows other code to run while tracking time.
- Scheduling tasks: It is used to execute tasks at specific intervals without stopping the main loop.
Arduino Syntax use
millis();
Arduino Syntax Explanation
- millis(): The function returns the number of milliseconds since the program began running. The value returned is a long unsigned integer.
Arduino code Example
unsigned long previousMillis = 0; // Store the last time an action occurred
const long interval = 1000; // Interval of 1 second
void setup() {
Serial.begin(9600); // Start serial communication
}
void loop() {
unsigned long currentMillis = millis(); // Get the current time in milliseconds
if (currentMillis - previousMillis >= interval) {
// Check if 1 second has passed
previousMillis = currentMillis; // Update the last action time
Serial.println("1 second has passed."); // Print message
}
}
Code Explanation
- previousMillis: Stores the last time an action was performed.
- interval: Defines the interval between actions (1 second or 1000 milliseconds).
- currentMillis = millis();: Retrieves the current time in milliseconds since the program started running.
- if (currentMillis – previousMillis >= interval);: Checks if 1 second (or the defined interval) has passed since the last action.
- previousMillis = currentMillis;: Updates the last action time to the current time.
- Serial.println(“1 second has passed.”);: Prints a message to the serial monitor every second.
Notes
- The millis() function keeps running continuously after the program starts. It rolls over and resets approximately every 49 days, as the value it returns exceeds the limit of a long unsigned integer.
- millis() is ideal for creating non-blocking delays, allowing the program to handle other tasks while tracking time.
- The millis() function is particularly useful in projects requiring precise timing, such as controlling motors, LEDs, or responding to sensor inputs at regular intervals.
- Use unsigned long variables to store the values returned by millis(), as the value can become very large over time.
micros() – Return Elapsed Time in Microseconds in Arduino
micros() is an Arduino function that returns the number of microseconds (one millionth of a second) that have passed since the program began running. This function provides higher resolution timing than millis(), making it useful for tasks that require precise and short time intervals. The value returned is a long unsigned integer and rolls over after approximately 70 minutes.
Use purpose
The micros() function is used for:
- High-resolution timing: Measuring time intervals with microsecond precision.
- Accurate event timing: Suitable for applications that need precise control, such as sensors, pulse-width modulation (PWM), or motor control.
- Non-blocking time tracking: Like millis(), it allows time tracking without halting other operations in the main loop.
Arduino Syntax use
micros();
Arduino Syntax Explanation
- micros(): Returns the number of microseconds since the program started running. It is a long unsigned integer.
Arduino code Example
unsigned long previousMicros = 0; // Store the last time an action occurred
const long interval = 1000000; // 1 second in microseconds
void setup() {
Serial.begin(9600); // Start serial communication
}
void loop() {
unsigned long currentMicros = micros(); // Get the current time in microseconds
if (currentMicros - previousMicros >= interval) {
// Check if 1 second (1,000,000 microseconds) has passed
previousMicros = currentMicros; // Update the last action time
Serial.println("1 second has passed (using micros)."); // Print message
}
}
Code Explanation
- previousMicros: Stores the last time an action was performed (in microseconds).
- interval: Defines the interval between actions (1 second or 1,000,000 microseconds).
- currentMicros = micros();: Retrieves the current time in microseconds since the program started running.
- if (currentMicros – previousMicros >= interval);: Checks if 1 second (or the defined interval) has passed since the last action.
- previousMicros = currentMicros;: Updates the last action time to the current time.
- Serial.println(“1 second has passed (using micros).”);: Prints a message to the serial monitor every second based on micros() timing.
Notes
- micros() provides more precise time measurements than millis() but rolls over approximately every 70 minutes when the value exceeds the maximum limit of a long unsigned integer.
- The resolution of micros() depends on the microcontroller, with most boards providing a 4-microsecond resolution (for example, on an Arduino Uno).
- micros() is ideal for applications requiring short, high-precision timing, such as handling sensor data, controlling motors, or implementing custom timing protocols.
- Like with millis(), ensure you use unsigned long variables to store the values returned by micros(), as they can become large over time.
delay() – Pause Execution for a Specified Time in Milliseconds in Arduino
delay() is a function in Arduino that pauses the execution of the program for a specified number of milliseconds. During this time, the Arduino stops executing other code, making it a blocking function. It is often used to create a delay between actions, such as blinking an LED or waiting for user input.
Use purpose
The delay() function is typically used for:
- Pausing execution: To wait between actions or events in your code.
- Timing sequences: Creating timed sequences like flashing LEDs or motor movements.
- Simple delays: Useful in situations where blocking the code execution is acceptable, such as in basic loops.
Arduino Syntax use
delay(milliseconds);
Arduino Syntax Explanation
- milliseconds: The number of milliseconds to pause the program. One second equals 1000 milliseconds.
Arduino code Example
int ledPin = 13; // Pin connected to the LED
void setup() {
pinMode(ledPin, OUTPUT); // Set pin 13 as output
}
void loop() {
digitalWrite(ledPin, HIGH); // Turn the LED on
delay(1000); // Wait for 1 second
digitalWrite(ledPin, LOW); // Turn the LED off
delay(1000); // Wait for 1 second
}
Code Explanation
- pinMode(ledPin, OUTPUT);: Configures pin 13 as an output to control the LED.
- digitalWrite(ledPin, HIGH);: Turns the LED on by setting pin 13 to HIGH.
- delay(1000);: Pauses the execution for 1 second (1000 milliseconds).
- digitalWrite(ledPin, LOW);: Turns the LED off by setting pin 13 to LOW.
- delay(1000);: Waits for another second before repeating the loop.
Notes
- delay() is a blocking function, meaning it pauses the entire program for the specified duration. While the program is paused, no other code can be executed.
- Use delay() in simple projects where blocking the code execution doesn’t affect performance or responsiveness, like turning an LED on and off.
- For projects that require multitasking or handling events while waiting, consider using millis() for non-blocking delays.
- The delay() function takes input in milliseconds, so delay(1000) pauses the program for 1 second.
delayMicroseconds() – Pause Execution for a Specified Time in Microseconds in Arduino
delayMicroseconds() is an Arduino function that pauses the execution of the program for a specified number of microseconds (one millionth of a second). Unlike delay(), which operates in milliseconds, delayMicroseconds() offers finer resolution, making it useful for applications that require very short, precise delays. However, just like delay(), this function is blocking, meaning no other code will run during the pause.
Use purpose
The delayMicroseconds() function is typically used for:
- High-precision timing: Creating very short and accurate delays for tasks such as pulse-width modulation (PWM), sensor readings, or communication protocols.
- Short pauses: It is useful when delays shorter than 1 millisecond are needed.
- Low-level control: Suitable for low-level hardware operations like controlling stepper motors or handling very fast sensor data.
Arduino Syntax use
delayMicroseconds(microseconds);
Arduino Syntax Explanation
- microseconds: The number of microseconds to pause the program.
Arduino code Example
int ledPin = 13; // Pin connected to the LED
void setup() {
pinMode(ledPin, OUTPUT); // Set pin 13 as output
}
void loop() {
digitalWrite(ledPin, HIGH); // Turn the LED on
delayMicroseconds(500000); // Wait for 500 milliseconds (500,000 microseconds)
digitalWrite(ledPin, LOW); // Turn the LED off
delayMicroseconds(500000); // Wait for another 500 milliseconds
}
Code Explanation
- pinMode(ledPin, OUTPUT);: Configures pin 13 as an output to control the LED.
- digitalWrite(ledPin, HIGH);: Turns the LED on by setting pin 13 to HIGH.
- delayMicroseconds(500000);: Pauses the program for 500,000 microseconds, which equals 500 milliseconds.
- digitalWrite(ledPin, LOW);: Turns the LED off by setting pin 13 to LOW.
- delayMicroseconds(500000);: Waits for another 500 milliseconds before repeating the loop.
Notes
- delayMicroseconds() provides finer control over timing than delay(), allowing delays as short as a few microseconds. However, accuracy decreases for delays over 16383 microseconds due to the overhead of function execution.
- As with delay(), delayMicroseconds() is a blocking function, which means it pauses the program and prevents other code from running during the delay.
- While delayMicroseconds() is precise for very short delays, it is not ideal for longer time intervals. For delays longer than 16383 microseconds, it’s better to use delay() or millis() for time tracking.
- The actual delay can vary slightly based on the clock speed of your Arduino board and the overhead required to call the function.
Common Problems and Solutions
- Code Freezes or Stops Working Problem: Using delay() in the loop causes the code to freeze. Solution: Use millis() or micros() for non-blocking delays, allowing the code to continue executing.
- Time Tracking Issues Problem: The program stops tracking time correctly after running for a long time. Solution: millis() and micros() reset after a certain period (49 days and 70 minutes, respectively). Use proper checks to handle this rollover.
- Inconsistent Timing with delayMicroseconds() Problem: Timing precision with delayMicroseconds() seems off. Solution: For delays longer than 16383 microseconds, use delay() instead, as delayMicroseconds() loses accuracy for longer intervals.
Chapter Summary
- millis() and micros() are non-blocking functions to measure elapsed time, while delay() and delayMicroseconds() are blocking functions that pause program execution.
- millis() and micros() track time since the program started running, making them ideal for multitasking projects.
- delay() is easy to use but stops the execution of other tasks.
FAQ
- What is millis() in Arduino?
millis() returns the number of milliseconds since the program started running and is useful for non-blocking time tracking. - How does delay() differ from millis()?
delay() pauses the program entirely for a specified amount of time, while millis() continues tracking time while other code runs. - What is the resolution of micros()?
micros() offers microsecond precision, with a typical resolution of 4 microseconds on most boards.
Simple MCQ Questions and Answers
- Which function allows you to track the number of milliseconds since the program started?
a) delay()
b) millis()
c) micros()
Answer: b) millis() - What does delayMicroseconds() do in Arduino?
a) Pauses execution for milliseconds
b) Pauses execution for microseconds
c) Tracks time since program start
Answer: b) Pauses execution for microseconds - When should you use millis() instead of delay()?
a) For precise microsecond timing
b) To create non-blocking delays
c) To pause program execution
Answer: b) To create non-blocking delays