////////////////////////////////////////////////////////////////////////////
//   Copyright : Диполь Ltd. 2005
//   Author : Vladimir Bushuev
//   e-mail : radiolab@front.ru
//
//	This code may be used in compiled form in any way you desire. This
//	file may be redistributed unmodified by any means PROVIDING it is 
//	not sold for profit without the authors written consent, and 
//	providing that this notice and the authors name is included.
////////////////////////////////////////////////////////////////////////////

#include "HARDWARE.h"
#include <string.h>

#include "Flash.h"
#include  "msp430x11x1.h"


#pragma memory=constseg(SegA)
	 unsigned char SegA[128];		//free
#pragma memory=default

 
  char Save=0;
  void FlashWrtByte(unsigned char *DataPtr,unsigned char byte)
{
    _DINT();
	do
    {
		FCTL3=FWKEY;			// Lock = 0 
		while(1)if(!(BUSY&FCTL3))break;
		FCTL1=FWKEY|WRT;		// WRT  = 1 
		DataPtr[0]=byte;			// Program Flash byte 
		while(1)if(!(BUSY&FCTL3))break;
		FCTL1=FWKEY;			// WRT  = 0 
		FCTL3=FWKEY|LOCK;		// Lock = 1 
    }
    while(DataPtr[0]!=byte);
	_EINT();
}

void FlashEraseSegment(unsigned char *SegPtr)
{
    _DINT();
	FCTL3=FWKEY;				// Lock   = 0 
    while(1)if(!(BUSY&FCTL3))break;
    FCTL1=FWKEY|ERASE;			// ERASE  = 1 
    SegPtr[0]=0;                       
    while(1)if(!(BUSY&FCTL3))break;
    FCTL1=FWKEY;				// ERASE  = 0 
    FCTL3=FWKEY|LOCK;			// Lock   = 1 
	_EINT();
}


void Write_Long(char count,unsigned long Data)
{
	unsigned char *Pt=(unsigned char *)&Data;

	FlashWrtByte(&SegA[count*3],Pt[0]);
	FlashWrtByte(&SegA[count*3+1],Pt[1]);
	FlashWrtByte(&SegA[count*3+2],Pt[2]);
}

 
void main(void)
{ char aa;
  
   WDTCTL = WDTPW|WDTHOLD|WDTTMSEL;
   
     P1OUT  = P1OUT_INIT; P1DIR  = P1DIR_INIT;                
    P2OUT  = P2OUT_INIT; P2DIR  = P2DIR_INIT;
 

 _DINT(); 
 
// void FlashInit(void)
//{
	while(1)if(!(BUSY&FCTL3))break;
	FCTL2=FWKEY|FSSEL_2|FN1;       //|FN1|FN0 Lock = 0, clock =SMCLK/8 
//}	
 

  FlashEraseSegment(SegA);  Write_Long(0,0x567689); 
     
  

    
P1DIR &=~BIT0;
P1IFG &=~BIT0;
P1IES |= BIT0; 
P1IE |= BIT0; 

    Write_Long(1,0x567689); 
   aa=2;
 
 _EINT();
 while(1){
 if(Save==1){Write_Long(aa,0x567689); aa++;}
 
}}


//************************************************************************
//*                    Key press/release ISR.
//************************************************************************
interrupt [PORT1_VECTOR] void KeyPressed_P1 (void)
{
_DINT();

 
  // P1IE |= OFF; 
Save=1;

 
 // P1IE &=~ OFF;
  P1IFG &=~ BIT0;

_EINT();
}