How to Add Delay in Microseconds in Arduino

This tutorial will discuss adding delay in microseconds in the code using the delayMicroseconds()
and micros()
functions in Arduino.
Add Delay in Microseconds in Arduino
Sometimes, in Arduino, we need to run a task for a specific time. For example, if we want to blink an LED, we have to turn the LED on for a particular amount of time, like one second, and then turn it off.
We can use the delayMicroseconds()
function in Arduino to add delay in microseconds. For example, consider we have to print some numbers on the serial monitor at a specific time interval.
If we print the numbers directly without adding a delay, the numbers will be printed so fast that we don’t even see the process because the microcontroller is fast. If we add some delay in the code, the numbers will be printed according to the delay.
One number will be printed. The program will wait for the delay, and the following number will be printed, etc.
For example, let’s print some random numbers on the serial monitor window and add some delay in microseconds in the code.
Example:
long MyRnd;
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0));
}
void loop() {
MyRnd = random(100);
Serial.println(MyRnd);
delayMicroseconds(1000);
}
Output:
1060
1001852
2003016
3004172
We used the delay()
function to add a delay in the code to see the output in the code. It took 1060 microseconds to execute the lines of code before the micros()
function.
The time it takes to execute an instruction depends on the type of Arduino board because different boards have different frequencies. To record time in milliseconds, we can use the millis()
function.
The millis()
and micros()
function does not halt any other process running in Arduino. We can use them with a conditional statement to perform the same task as the delay()
and delayMicroseconds()
function.
We can use the millis()
function to check the time, and using an if
statement, we can run a task for a specific amount of time.
For example, let’s print some text on the serial monitor and add a one-second delay to print the text with an interval of one second.
Example:
long t1 = 0;
long t2 = 0;
long t;
void setup() { Serial.begin(9600); }
void loop() {
t1 = millis();
t = t1 - t2;
if (t > 1000) {
Serial.println("Hello World");
t2 = t1;
}
}
Output:
Hello World
Hello World
Hello World
We used the difference between time intervals in the above code to get the time elapsed. If the time is greater than one second or 1000 milliseconds, we will print the text and change the second time interval to the first time interval to make the difference zero.
The output shows that the text is printed with a time difference of one second on the serial monitor window.