4. Delay
Delay functions are very common in computer programming. They can pause program execution for a period of time to meet various application requirements.
4.1 Purpose of Delay
In Arduino or other microcontroller programming, delay is widely used for the following reasons:
Handling Hardware
Many hardware devices need some time to respond to a command. For example, if a program starts a motor and immediately checks its status, you may get an incorrect reading because the motor may not have had enough time to start rotating. In this case, use the delay() function to make the system wait for a period of time so the motor has enough time to respond.
User Interaction
We often need delay effects in user interaction. For example, when a buzzer plays music, there must be a short silent interval between notes. Or, when blinking an LED, the "on" and "off" states need a delay to control the blinking speed.
Saving Energy
In some applications, such as battery-powered systems, if the system keeps running at high speed when it is not needed, battery life will be greatly reduced. In this situation, the system can enter standby or low-power mode after a period of time until the next processing cycle arrives.
Timed Operations
In many projects, specific operations need to be performed at certain times. For example, in an automatic irrigation system, watering may need to occur at a specific time every day. In interval measurement, data may be collected once every certain period of time.
Although delay functions are useful in many cases, their blocking behavior must be considered. Excessive dependence on blocking delays may cause the program to respond slowly to other events. To perform multitasking better on Arduino, you can also learn non-blocking delay programming techniques.
❓What is a blocking delay?
A blocking delay means that when an operation or function needs time to complete during program execution, the program pauses until the operation is complete. During this period, the program is blocked. Blocking delays may slow down the program or make it appear frozen. For example, suppose you want to boil water for tea. Normally, you place a kettle on the stove and wait until the water boils before using it. This process contains a blocking delay. When you place the kettle on the stove, the program can be seen as "waiting" for the water to boil. During this waiting process, you cannot immediately get hot water for tea; you must wait patiently until the water boils. During that time, you cannot do anything unrelated to boiling water because you need to watch the kettle and wait for the right moment. Even if there is an emergency at home, you are still waiting for the water to boil.
4.2 Delay Implementation
In Arduino, delay operations can be implemented using the delay() function. delay() takes only one parameter, the number of milliseconds to delay. This function blocks code execution, causing the program to pause for the specified time before continuing.
For example, to implement a 1-second delay in Arduino, write:
delay(1000); // Delay for 1000 ms, equal to 1 secondNote that because delay() is blocking, the program cannot perform other tasks during the delay. For programs that need to process multiple tasks at the same time or use non-blocking delays, use the millis() function to get the number of milliseconds since the program started and use it for timing.
The following is an example of a non-blocking delay using millis():
const int ledPin = 48; // Define the LED pin
unsigned long previousMillis = 0;// Define a variable to record time
unsigned long interval = 1000; // Delay for 1000 ms, equal to 1 second
bool ledState = LOW;// Define the LED state as low level
// Run only once
void setup()
{
// Set the ledPin pin to output mode
pinMode(ledPin, OUTPUT);
}
// Loop continuously
void loop()
{
// Define a variable to store the value returned by millis()
unsigned long currentMillis = millis();
// If the current running time minus the previous running time is greater than 1000 ms,
// it means 1000 ms has passed
if (currentMillis - previousMillis >= interval)
{
// Update the previous time to the current time for the next calculation
previousMillis = currentMillis;
// Toggle the LED state
ledState = !ledState;
digitalWrite(ledPin, ledState);
}
// Other tasks can be executed here without waiting for a delay
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
In this example, the millis() function and the previousMillis variable are used to track time and implement a delay. This method handles multitasking more efficiently and is not affected by blocking delays.
4.3 Blinking LED Verification
Set GPIO48, which is connected to the LED on the development board, to output mode. Use the delay function delay() to control the LED so it turns on for a while and off for a while, creating a blinking effect.
void setup()
{
// Set GPIO48 as output mode
pinMode(48,OUTPUT);
// Set pin 48 to output low level
digitalWrite(48,LOW);
}
void loop()
{
// Set pin 48 to output low level
digitalWrite(48,LOW);
// Delay for 100 ms
delay(100);
// Set pin 48 to output high level
digitalWrite(48,HIGH);
// Delay for 100 ms
delay(100);
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
4.4 Blinking LED Effect
After the code is downloaded, the LED marked G48 on the development board will repeatedly turn on and off.