Watchdog in MCUSR always on

Hi, I am trying to setup (interruptable) sleep with watchdog for polling some other sensors, but for some reason I find myself seeing the WDRF flag in MCUSR always on, even if I push the reset button/plug out-in the USB cable (no extrernal power ATM). I am using UNO, but not sure what bootloader (as a newbie I haven’t touched the ‘Burn bootloader’ menu item yet).

This is my code:

#include <avr/power.h>
#include <avr/sleep.h>
#include <avr/wdt.h>

// some code copy-pasted from avr/wdt.h
uint8_t mcusr_mirror __attribute__ ((section (".noinit")));
void get_mcusr(void) \
  __attribute__((naked)) \
  __attribute__((section(".init3")));
void get_mcusr(void)
{
  mcusr_mirror = MCUSR;
  MCUSR = 0;
  wdt_disable();
}

void setup() {  
  pinMode(13, OUTPUT);

  // blink to show me that the setup is running
  for (int i = 0; i < 5; ++i) {
    digitalWrite(13, HIGH);
    delay(200);
    digitalWrite(13, LOW);
    delay(200);
  }
  // here we test the status
  if (mcusr_mirror & 8) {  
    digitalWrite(13, HIGH);
  } else {
    digitalWrite(13, LOW); // this shouldn't be necessary
  }
  delay(1000);
}

// void onMove() {  
// }

void sleep() {
  cli();
  wdt_enable(WDTO_4S);
  wdt_reset();
    
  power_all_disable();   // turn off all modules
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
  sleep_enable();
//  attachInterrupt(digitalPinToInterrupt(PIR_SENSOR_PIN), onMove, CHANGE);
  sei();
  sleep_cpu();
//  detachInterrupt(digitalPinToInterrupt(PIR_SENSOR_PIN));
  power_all_enable();
  wdt_disable();
}

void loop() {           
    sleep();
}

Thank you for hints. Googling around showed that some problems (like MCUSR == 0) were caused by bootloader but those were mostly old posts and the issue seemed fixed.

Yep. This is how the bootloader works - it uses a watchdog reset to re-initialize the AVR before running your sketch, whether it decides there is a new sketch to load, or not.)

Recent versions of optiboot have been change to allow applications to detect whether a watchdog is from the bootloader or from the application - basically, if the application takes care to reset MCUSR to 0, then actual watchdog timeouts from the application will have ONLY WDRF set, while watchdogs that occurred during the bootloader will have WDRF and some other flag (usually EXTRF) set.

The dance is delicate. See:
https://github.com/Optiboot/optiboot/blob/master/optiboot/examples/test_reset/test_reset.ino

(and, the standard bootloader is not "recent." You'll need to install a newer version.)