//------------------------------------------------- //Company: ZLGMCU //MCU: P89V51RD2 //Crystal: 11.0592Mhz //Writer: ZLG900 //Function: Read/Write Cat25C02 //------------------------------------------------- #include "reg52.h"
sfr SPCR=0xD5; //SPI Control sfr SPSR=0xAA; //SPI Status sfr SPDAT=0x86; sbit CS=P1^4; //sbit SI=P1^5; //sbit SO=P1^6; //sbit SCK=P1^7;
//------------------------------------ //Delay(): delay 4 ms,(11.0592MHz) //------------------------------------ void Delay() { int i; for(i=0x00;i<0x500;i++); }
//------------------------------------ //SPI_Init: Init SPI //------------------------------------ void SPI_Init() {
SPCR=0x56; //0101 0110 ,Disable SPI Interrupt, Enable SPI, Master Mode,CHOL=0,CHOA=1; SPSR=0x00; //0000 0000 ,Clr SPIF CS=1; // ES=1; // EA=1;
}
//------------------------------------ //EnableWrite: //function: Enable=0,Disable write // Enable=1,Enable write //------------------------------------ void EnableWrite(char Enable) { CS=0;
if(Enable==0) { SPDAT= 0x04; //Disable Command } else { SPDAT= 0x06; //Enable Command } while((SPSR&0x80)==0); SPSR=0x00;
CS=1; }
//------------------------------------ //ReadData: //------------------------------------ void ReadData(unsigned char address, unsigned char *buf, unsigned char length) { CS=0;
SPDAT=0x03; //Read Data Command while((SPSR&0x80)==0); SPSR=0x00; SPDAT=address; //Read address while((SPSR&0x80)==0); SPSR=0x00;
while(length--) { SPDAT=0xff; while((SPSR&0x80)==0); *buf=SPDAT;
buf++; SPSR=0x00; }
CS=1; }
//------------------------------------ //ReadStatus //------------------------------------ unsigned char ReadStatus (void) { unsigned char status;
CS = 0;
SPDAT = 0x05; //Read Status Command while ((SPSR & 0x80) == 0); SPSR=0x00;
SPDAT = 0xFF; //Read SPI status while ((SPSR & 0x80) == 0); status = SPDAT;
SPSR=0x00; CS = 1;
return (status); }
//------------------------------------ //WriteData: //------------------------------------ void WriteData(unsigned char address,unsigned char *buf,unsigned char length) {
EnableWrite(1); while (ReadStatus() & 0x01);
CS = 0; SPDAT = 0x02; //Write Data Command while((SPSR&0x80)==0); SPSR=0x00;
SPDAT = address; //Write address while((SPSR&0x80)==0); SPSR=0x00;
for (; length>0 ;length-- ) { SPDAT = *buf; while((SPSR&0x80)==0); SPSR=0x00; address++; buf++; } CS = 1;
Delay(); EnableWrite(0); }
//------------------------------------ //main: //------------------------------------ void main() { unsigned char temp[8]; unsigned char SaveData[8]={0x01,0x02,0x03,0x04,0x05,0x06,0x70,0x80};
SPI_Init();
while(1) {
WriteData(0x00,SaveData,8); ReadData(0x00,temp,8);
} }
//------------------------------------ //END //------------------------------------
|