飞思卡尔单片机DZ60---EEPROM读写

//向EEPROM中写入数据,然后读出数据,赋值给PORTD,点亮相应的LED灯

#include <hidef.h> /* for EnableInterrupts macro */
#include "derivative.h" /* include peripheral declarations */


#define uint unsigned int
#define uchar unsigned char


#define LED     PTDD
#define LED_DIR PTDDD

#define LED_OFF 0XFF


void Read_EEPROM(uint start_addr, uchar *pReadbuf, uchar length);
void Write_EEPROM(uint start_addr, uchar *pData, uchar length);

//uchar Data[6] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
//uchar Readbuf[6] = {0};

uchar Data[6] = {0xFE, 0xFD, 0xFB, 0xF7, 0xEF, 0xDF};
uchar Readbuf[6] = {0XFF};

uchar i = 0;
uint j = 60000;


/*************************************************************/
/*                  初始化总线时钟PEE模式                    */
/*              外部晶振频率为4MHz,总线频率16MHz            */
/*************************************************************/
void INIT_MCG(void) 
{
  MCGC2=0x36;        
  while(!MCGSC_OSCINIT);     
  MCGC1=0xb8;
  while(MCGSC_IREFST);
  while(MCGSC_CLKST!=0b10);
  MCGC2_LP = 1;
  MCGC1 = 0x90;
  MCGC3 = 0x48;     
  MCGC2_LP = 0;
  while(!MCGSC_PLLST);
  while(!MCGSC_LOCK);
  MCGC1 = 0x10;
  while(MCGSC_CLKST!=0b11);
}


void main(void) {

  DisableInterrupts;
  SOPT1 = 0;
  INIT_MCG();
  
  LED_DIR = 0XFF;
  LED = LED_OFF;
  
  
  EnableInterrupts; /* enable interrupts */
  /* include your code here */
  

  
  FCDIV = 73;//设置分频,16MHZ/8/(9+!)在150k到200khz之间
  
  //EEPROM整个空间为2*1024BYTES,地址为0x1400到0x17FF
 
  //写入数据部分
  Write_EEPROM(0X1400, Data, 6);
  
  //读出数据部分
  Read_EEPROM(0X1400, Readbuf, 6);

  while(1) 
  {
      for(i = 0; i < 6; i++) 
      {
        LED = Readbuf[i];
        while(j--);
    
      }
  }

  
  
  


  for(;;) {
    __RESET_WATCHDOG(); /* feeds the dog */
  } /* loop forever */
  /* please make sure that you never leave main */
}


void Write_EEPROM(uint start_addr, uchar *pData, uchar length) 
{
  uchar i;
  uchar *pAddr;
  
  if(FSTAT_FACCERR == 1)
    FSTAT_FACCERR = 1;//通过写入1来清除错误标记
    
   pAddr = (uchar *)(start_addr);//指定地址
   *pAddr = 0x01;
   
   
   FCMD = 0X40;//擦除命令
   FSTAT_FCBEF = 1;//启动命令
   
   asm{         //等待4个bus cycle
   NOP
   NOP
   NOP
   NOP
   }
   
   while(FSTAT_FCCF == 0);//等待完成
   
   
   for(i = 0; i < length; i++) 
   {
   
      if(FSTAT_FACCERR == 1)
        FSTAT_FACCERR = 1;
      
      pAddr = (uchar *)(start_addr + i);
      *pAddr = pData[i];
      
      FCMD = 0X20;//写入命令
      FSTAT_FCBEF = 1;// 启动命令
      asm
      {
        NOP
        NOP
        NOP
        NOP
      }
      
      while(FSTAT_FCCF == 0);//等待完成
      
   }

}


void Read_EEPROM(uint start_addr, uchar *pReadbuf, uchar length) 
{
    uchar i;
    uchar *pAddr;
    
    for(i = 0; i < length; i++) 
    {
      pAddr = (uchar *)(start_addr);
      pReadbuf[i] = *pAddr;
      start_addr++;
    }

}




你可能感兴趣的:(飞思卡尔单片机DZ60---EEPROM读写)