1

I'm trying to reset my program from software using the third method described here: Reset an Arduino Uno in code

The function is basically showing some data on an OLED display and afterwards should reset the processor

void setup() {
  MCUSR = 0;
}

void showCharacter(int char_number) {

  // [...]

  display.println(character_buffer);
  display.display();

  for (int j = 0; j < 3; j++) {
    enableLED(x, y);
    publishLEDs();
    delay(500);
    clearLEDs();
    publishLEDs();
    delay(500);
    Serial.println(j);
  }

  keyscan.sleep();

  // Reset system
  wdt_enable(WDTO_15MS); // turn on the WatchDog and don't stroke it.
  for (;;) {}
}

For whatever reason it makes a difference if the Serial.println() line is there. If the line is there, the code behaves as expected. The LED blinks three times, afterwards the Arduino is reset.

If I remove that line however, the LED continues to blink infinitely and the code does not reset. I really have no idea why that line has such a big difference, I wouldn't expect any difference to be honest. Anybody has an idea what's going on?

Edit:

I got a hint from a friend of mine that using the volatile keyword in the for loop could fix the problem. He vaguely remembered having a similar problem somehow related to compiler optimisation. And indeed, the following code works as expected:

for (volatile int j = 0; j < 3; j++) {
  enableLED(x, y);
  publishLEDs();
  delay(500);
  clearLEDs();
  publishLEDs();
  delay(500);
}

So let me rephrase my question a little bit - what is happening here, why is the volatile keyword needed?

Daniel
  • 111
  • 4

0 Answers0