How to get the cause of reset in arduino uno

Hi, I am using an Arduino Uno and I need to evaluate what has been the cause of the reset, I am using this code but I always have the register MCUSR value equal to 2, what could be my error?

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.print("MCUSR: ");
  Serial.println(MCUSR);

  if (MCUSR & (1 << PORF)) {        // Power-on Reset
    Serial.println("Cause of Reset = Power-on Reset" );
  }
  else if (MCUSR & (1 << EXTRF)) {  // External Reset
    Serial.println("Cause of Reset = External Reset" );
  }
  else if (MCUSR & (1 << BORF)) {   // Brown-Out Reset
    Serial.println("Cause of Reset = Brown-Out Reset" );
  }
  else if (MCUSR & (1 << WDRF)) {   // Watchdog Reset
    Serial.println("Cause of Reset = Watchdog Reset" );
  }
  MCUSR = 0;
}

void loop() {
}

How are you stimulating this sketch to reset in all the ways you want it to recognize?

What do you expect for the output?

a7

https://www.idogendel.com/en/archives/623

The bootloader runs before your sketch, and resets the flag for the cause of the reset. Optiboot can pass the data to your code, but you need a more recent version than the one shipped on the UNO.

1 Like

Please can you give more details on how to achieve this

Did you research it? Optiboot must be documented...

Does not help that the old example code of test_reset.ino seems to no longer exist.
This looks like the current example code, note that it REQUIRES a newer version of optiboot than the standard one on an UNO.

https://github.com/Optiboot/optiboot/blob/master/optiboot/examples/demo_reset/demo_reset.ino

You could just remove the bootloader entirely and load your sketch using an ISP, then you do not have to worry about optiboot messing with MCUSR.