Error:
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.
Solution :
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;
}
}
For LED device :
unsigned long previousMillis = 0;
const long interval = 1000;
int ledState = LOW;
void setup() {
// Initialize serial communication at a baud rate of 9600
Serial.begin(9600);
// Set pin 13 as an output (often connected to the built-in LED on Arduino boards)
pinMode(13, OUTPUT);
}
void loop() {
// Get the current time in milliseconds since the program started
unsigned long currentMillis = millis();
// Check if the specified interval has passed
if (currentMillis - previousMillis >= interval) {
// Save the last time the LED was toggled
previousMillis = currentMillis;
// If the LED is off, turn it on, and vice versa
if (ledState == LOW) {
ledState = HIGH;
Serial.println("LED is ON");
} else {
ledState = LOW;
Serial.println("LED is OFF");
}
// Set the LED with the ledState of the variable
digitalWrite(13, ledState);
}
}