Non-blocking code lets your Arduino do many things at once without waiting. It keeps your program running smoothly and quickly.
0
0
Non-blocking code architecture in Arduino
Introduction
When you want to blink an LED while reading a sensor without stopping either task.
When you need to check buttons and control motors at the same time.
When you want to keep your program responsive to inputs while doing other work.
When you want to avoid delays that freeze your Arduino and make it unresponsive.
Syntax
Arduino
unsigned long previousMillis = 0; const long interval = 1000; void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; // Do something every interval } // Other code runs here without delay }
millis() returns the number of milliseconds since the Arduino started.
Use if checks with millis() instead of delay() to avoid stopping the program.
Examples
Blinks the built-in LED every 500 milliseconds without stopping other code.
Arduino
unsigned long previousMillis = 0; const long interval = 500; void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); } // Other tasks can run here }
Prints a message every 2 seconds while allowing continuous sensor reading.
Arduino
unsigned long previousMillis = 0; const long interval = 2000; void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; Serial.println("Checking sensor..."); } // Read sensor continuously here }
Sample Program
This program toggles the built-in LED every second and prints a message. It never stops running, so you can add more tasks easily.
Arduino
unsigned long previousMillis = 0; const long interval = 1000; void setup() { pinMode(LED_BUILTIN, OUTPUT); Serial.begin(9600); } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); Serial.println("LED toggled"); } // Here you can add other code that runs without delay }
OutputSuccess
Important Notes
Never use delay() if you want your Arduino to do many things at once.
Use millis() to check how much time has passed and decide when to act.
Keep your loop() running fast by avoiding long or blocking code.
Summary
Non-blocking code lets your Arduino multitask smoothly.
Use millis() and time checks instead of delay().
This keeps your program responsive and ready for many tasks.