Jump to content

Saving data to flash on power down

Recommended Posts

Here is a simple solution to the problem I had, saving data when power goes down.

There are two parts needed, a diode (1N4148) and a capacitor (~47uF.)

The way it works, you isolate main power from MCU and connect capacitor on the MCU's side.

One of the pins is connected to the main power and will trigger an interrupt.

In the interrupt routine, we will be saving data to flash.

This is a simple proof of concept, the final code should include low voltage detection for situations like dying battery.





#include  "msp430g2231.h"

unsigned int data = 0;
unsigned int * const savedDataPtr = (unsigned int *)(0x1000);

void main(void) {

   P1DIR &= ~BIT1;
   P1IE |= BIT1;
   P1IES |= BIT1;
   P1IFG &= ~BIT1;
   P1REN |= BIT1;
   P1OUT &= ~BIT1;

   P1DIR |= BIT0;
   P1OUT |= BIT0;

   data = *savedDataPtr;
   if(data == 0xFFFF)
       data = 100;

   unsigned int counter = data;


   while(1) {
       counter = data;
       while(counter > 0) {
       P1OUT ^= BIT0;

// Port 1 interrupt service routine
#pragma vector=PORT1_VECTOR
__interrupt void Port_1(void) {

   P1OUT &= ~BIT0;
   data += 100;

   // Save value
   FCTL2 = FWKEY + FSSEL0 + FN1;
   *savedDataPtr = 0;
   *savedDataPtr = data;

   P1IFG &= ~BIT1;

Share this post

Link to post
Share on other sites

Sorry to be bumping an old thread....Thanks for the code though Rob G! Nice application and thanks for sharing!


Question, is it safe not to have delay between when you erase and write to flash? Bulk erase time is specified as a min of 20ms. Should there be a delay between the erase/write?

Share this post

Link to post
Share on other sites

When you erase from Flash, which what the above example does, execution of your program will be halted until erase cycle is completed. Delay is not needed.

Share this post

Link to post
Share on other sites

Note.... TI made one rather interesting  :crazy:  memory controller that only works with a clk of 476khz to 257khz. See Section 7.3.1 of the G series usermanual. Basically your going to have to tweak the divider values of FCTL2 to get this to work consistently with your MCU as well as force block erases.

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...