Home > Back-end >  Can't get past for/while loop in Arduino
Can't get past for/while loop in Arduino

Time:12-09

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

CodePudding user response:

Adding volatile to avoid being removed by optimization works.

volatile unsigned long i = 0;

CodePudding user response:

The arduino compiler by default runs with all optimizations enabled, to reduce code size and improve speed. Since at least with the Arduino IDE, source-line debugging is not possible on the Arduino itself, this normally doesn't make a visible difference for development. The above code snippet is a rare example where it does.

How to disable optimization, if one really wants to do it, is described in this question: VSCode disabling Arduino compilation optimizations for debugging (thanks @dmaxime).

  • Related