本帖最后由 tianm 于 2011-11-28 11:21 编辑
下面例子是Qiaohaikun先生几年前一直用在MSP430FG4618...使用过的,一直都挺好使。希望在此分享出来能帮助到有需要的网友们。同样,希望各网友们如有精品程序例子的话同样可以发贴。人人为我,我为人人!
复制代码 - #include "msp430xG46x.h"
- void WriteFlashErrorNum(void);
- //----------------------------------------------------------------------
- //功能:从flash中读出数据,只需给出首地址和取出数据的数量
- //日期:2006.12.13
- //输入:waddr为flash的地址,length为数据长度
- //输出:无
- //----------------------------------------------------------------------
- void ReadFlash(unsigned long int waddr,unsigned int length)
- {
- unsigned char i=0;
- if(FlashMangleFlag==0)
- {
- while(FCTL3 & BUSY);
- if(length>64) length=64;
- while(length--)
- {
- Internal_flashdata[i++]=__data20_read_char(waddr++);
- }
- }
- }
- //----------------------------------------------------------------------
- //功能:段擦除;
- //日期:2006.12.13
- //输入:waddr为flash的地址,
- //输出:无
- //----------------------------------------------------------------------
- //void EraseFlashOneBlock(unsigned long int waddr)
- void EraseFlash(unsigned long int waddr)
- {
- if(FlashMangleFlag==0)
- {
- if((waddr>=0x1f400) && (waddr<0x20000))
- {
- while(FCTL3 & BUSY);
- _DINT();
- FCTL2 = FWKEY + FSSEL1 + FN4;
- FCTL3 = FWKEY; // Clear Lock bit
- FCTL1 = FWKEY + ERASE; // Set Erase bit
- __data20_write_char(waddr,0); // Dummy write to erase Flash segment
- while(FCTL3 & BUSY);
- FCTL3 = FWKEY + LOCK; // Reset LOCK bit
- _EINT();
- }
- }
- }
- //----------------------------------------------------------------------
- //功能:将数据写入flash;
- //日期:2006.12.13
- //输入:waddr为flash的地址,length为数据长度,*buf为指向数据的指针
- //输出:无
- //----------------------------------------------------------------------
- unsigned char WriteFlash(unsigned long int waddr,unsigned char *buf,unsigned int length)
- {
- unsigned int i;
- unsigned char temp,ErrorFlag = 0;
- if(FlashMangleFlag==0)
- {
- if((waddr>=0x1f400) && (waddr<0x20000))
- {
- while(FCTL3 & BUSY);
- _DINT();
- FCTL2 = FWKEY + FSSEL1 + FN4;
- FCTL3 = FWKEY; // Clear Lock bit
- FCTL1 = FWKEY + WRT; // Set WRT bit for write operation
- for(i=0;i<length;i++)
- {
- __data20_write_char(waddr,*buf); // Write value to flash
- temp = __data20_read_char(waddr); // Read one byte
- if(temp!=(*buf)) // 判断读出的数据和写入的数据是否相当
- {
- ErrorFlag = 1; //写入flash操作错误标志
- ErrorFlashNum ++ ;
- }
- waddr++;buf++;
- }
- while(FCTL3 & BUSY);
- FCTL1 = FWKEY;
- FCTL3 = FWKEY + LOCK; // Reset LOCK bit
- _EINT();
- if(ErrorFlag == 1) WriteFlashErrorNum();
- }
- }
- return ErrorFlag;
- }
|