In this article you will learn about concurrency on the arduino. Concurrency is a way of doing multiple things on the Arduino seemingly at the same time. This is great for making your code more responsive.
Why use concurrency
Concurrency allows for more efficient use of the Arduino's processing power. Instead of waiting idly for a task to complete, the Arduino can perform other operations. This is particularly useful in applications like:
- Home automation: Managing multiple sensors and actuators.
- Robotics: Handling sensor input while controlling motors.
- User interfaces: Responding to user inputs without delay
Limitations of the delay() function
When doing multiple things on the Arduino, one usually uses the delay() function. Although this works for simple programs, this function blocks all other code. Instead, we should be using the millis() function.
The millis() function returns the time in milliseconds since the Arduino started executing code.
Millis function example
When using the millis() function for concurrency we need to log the time at a certain point, and then we need to compare this value to the current time by subtracting the current time with the last time, and check if that is more than or equal to the specified delay. When we have done this, we can then set the lastTime variable to the current time.
unsigned long lastTime = millis();
unsigned long currentTime = 0;
const int delayTime = 1000;
void start() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
currentTime = millis();
if (currentTime - lastTime >= delay) {
lastTime = currentTime;
// Operation to be run here.
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}
}