Can't get past for/while loop in Arduino

New to Arduino, I have tried to make a for or a while loop to do a delay, instead of the delay() function. Have tried a LOT of values but the LED remains HIGH, it works if I use the delay() function. Note that I'm not going to use this code as delay, I just tried it and now I can't understand what goes wrong.
Board is a Nano Every, I use Arduino IDE, Fcpu = 8MHz.

const byte  ledPin = 13;
byte  ledState = HIGH; 
pinMode(ledPin, OUTPUT);
void loop() {
  unsigned long i = 0;
   // read the state of the switch into a local variable:
  //enaState = digitalRead(sw1);
  //dirState = digitalRead(sw2);
  
  while (i < 10000000)
  {
    i++;
  }
  //delay(1000);
  ledState ^= 1;
  digitalWrite(ledPin, ledState);
  i = 0;
 
}

the code optimiser sees that the loop does nothing and thus gets rid of it to give you faster/smaller code :wink:

use delay() or millis()

But why ? Because you heard that using delay() is bad ?

Well, using a loop of any kind to replace it is equally as bad!

Using delay() can be bad because it blocks the Arduino from performing other tasks, and simply wastes time. Using a loop to replace delay is bad for the same reasons.

Have a look at the Blink Without Delay example in the IDE (File->examples->02.digital->Blink Without Delay)

"Imagine how much faster the program would be if I just skipped to the answer!" - The Compiler

Results:

  unsigned long i = 10000000;

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