I am using an SD-Card (one file only, FAT-16) with an ATmega32 through SPI, and I am thinking about some unexpected conditions, like a power failure.
Well, in my application (a kind of data logger) I do open a file and it will remains open for a time (some hours). So I did think, how may I close the file before an unexpected power failure?
I know that I can detect a source of a reset, looking for the MCUSR register, doing something like this:
#define POWERONRST 'P'; #define EXTERNALRST 'E'; #define BROWNOUTRST 'B'; #define WATCHDOGRST 'W'; char rstsource; ... if (MCUSR & 1) // POR = Power-on Reset rstsource = POWERONRST; else if (MCUSR & 2) // EXR = External Reset rstsource = EXTERNALRST; else if (MCUSR & 4) // BOR = Brown-Out Reset rstsource = BROWNOUTRST; else // WDR = Watchdog Reset rstsource = WATCHDOGRST; // MCUSR = 0; // Init flags ...
So, "rstsource" will contain a character indicating a source of the reset.
To work around this unexpected situation, I need to call the function that performs the closing of the file, say "CloseFile ();".
My questions are:
1 - Detecting the unexpected reset by BOD (via interrupt) seems to be the best way?
2 - How long do I have to perform the "CloseFile ();" function (using an external crystal of 11.0592MHZ)?
Thank you in advance.