Detect restart reason under MegaCoreX

I’m using MegaCoreX on the Atmega4808.
I wish to find the reason for the resets I have, but could not find the code to do so.

It seems that MegaCoreX clears the RSTCTRL.RSTFR when it loads.
I tried to run this with ChatGPT, but all the codes I got from it always return 0x0 or 0x8 regardless if I power up the board or let the watchdog reset it.

How can I read the reason for the last boot?

Apparently ChatGPT never read the bootloader source:

    ch = RSTCTRL.RSTFR;   // get reset cause
    .
    .
    .
    RSTCTRL.RSTFR = ch; //clear the reset causes before jumping to app...
    GPIOR0 = ch; // but, stash the reset cause in GPIOR0 for use by app...

Thanks!
I found that optiboot_x.c reads the flag, but I'm not that good programer to find the GPIOR0 part.

With this code:

#include <avr/io.h>
#include <avr/eeprom.h>
#include <avr/wdt.h>

void printResetCause(uint8_t cause) {
  Serial.print("Reset cause: 0x");
  Serial.println(cause, HEX);

  if (cause & RSTCTRL_PORF_bm) Serial.println("Power-on Reset");
  if (cause & RSTCTRL_EXTRF_bm) Serial.println("External Reset");
 // if (cause & RSTCTRL_BODRF_bm) Serial.println("Brown-out Reset");
  if (cause & RSTCTRL_WDRF_bm) Serial.println("Watchdog Reset");
  if (cause & RSTCTRL_SWRF_bm) Serial.println("Software Reset");
  if (cause == 0x00) Serial.println("Unknown or cleared reset cause");
}

void(* resetFunc) (void) = 0; //declare reset function @ address 0

void setup() {
  Serial.begin(9600);
  delay(500);  // Give time for Serial to initialize

  uint8_t hw_reset = GPIOR0; //RSTCTRL.RSTFR;  // Read hardware reset flags immediately
  printResetCause(hw_reset);

  int a=1;
  if (a) {
    Serial.println("Triggering watchdog reset...");
    wdt_enable(WDT_PERIOD_8KCLK_gc);  // ~8 seconds timeout
    while (true);  // Wait for WDT to fire
  } else {
    Serial.println ("reset by code:");
    delay(5000);
    resetFunc();
  } 
}

void loop() {
}

I get 0xc on first power up.
0x8 when a=1 and the watch dog makes the reboot.
but also 0x8 when a=0 and the program makes the reboot.

Is there a way to seperate the two?

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