unsigned long previousMillis = 0UL;
unsigned long interval = 1000UL;
void setup()
{ /* do setup */ }
void loop()
{
/* other code */
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval)
{
/* The Arduino executes this code once every second
(interval = 1000 (ms) = 1 second).
*/
// Don't forget to update the previousMillis value
previousMillis = currentMillis;
}
}
Note how the loop()-method in the example sketch above can execute code with every iteration and some other code only once every second. This behavior is another benefit of using the millis()-method instead of delay(). With a delay-call, the entire program would halt for a second. When using millis(), ensure that you update the “previousMillis” variable somewhere in the if-block to ensure that the timings remain correct in consecutive iterations of the loop()-method.*
I moved your topic to an appropriate forum category @kanansananse.
In the future, please take some time to pick the forum category that best suits the subject of your topic. There is an "About the _____ category" topic at the top of each category that explains its purpose.
The delay function in programming pauses the execution of code for a specified duration. An error here could arise from incorrect usage of the delay function, which might lead to unexpected program behavior or inaccurate timing delays.