Jump to content
43oh

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.

 

post-197-135135497427_thumb.png

 

 

#include  "msp430g2231.h"

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


void main(void) {
   WDTCTL = WDTPW + WDTHOLD;

   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;

   _bis_SR_register(GIE);

   while(1) {
       counter = data;
       while(counter > 0) {
           _delay_cycles(1000);
           counter--;
       }
       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;
   FCTL1 = FWKEY + ERASE;
   FCTL3 = FWKEY;
   *savedDataPtr = 0;
   FCTL1 = FWKEY + WRT;
   *savedDataPtr = data;
   FCTL1 = FWKEY;
   FCTL3 = FWKEY + LOCK;

   P1IFG &= ~BIT1;
}


Link to post
Share on other sites
  • 1 year later...

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?

Link to post
Share on other sites
  • 1 year later...

Join the conversation

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

Guest
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...