Delay Function Error Code

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);

}
}

Welcome to the forum

As your topic does not relate directly to the installation or operation of the IDE it has been moved to the Programming Questions category of the forum

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the < CODE/ > icon above the compose window) to make it easier to read and copy for examination

https://forum.arduino.cc/t/how-to-get-the-best-out-of-this-forum

I am not sure what the point of your topic is but if you are trying to illustrate the use of millis() for timing then can I suggest that you post a sketch that compiles

1 Like

Please edit your post to add code tags.

Instructions for posting are in the "How to get the best out of this forum" post.

1 Like

not clear what incorrect usage of delay() you are referring to. Can you provide some examples?

are you familiar with Blink without Delay

No, it is not. This is the worst chatGPT/copy/paste ever.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.