用GCC写的AT24C64接口程序
扫描二维码
随时随地手机看文章
//AT24C64supportfunctionsusingATMEGA'sTWI
//PIN-WPishard-wiredtoGND
//fuctionsworkbetteroutsideinterruptroutines
//byMXH,2003/07/30
#include"DStruct.h"
#include
//CONSTANTSDEFINITIONFOREEPROM
#defineEEADDR0
#defineEEWR0
#defineEERD1
//TWINT*NOT*setafterSTOPconditionissent
//checkstatus?
//TWSTOisclearedbyhardware
#defineTwiStop()TWCR=_BV(TWINT)|_BV(TWEN)|_BV(TWSTO)
#defineTwiStart()TWCR=_BV(TWINT)|_BV(TWEN)|_BV(TWSTA)
#defineTWI_STATUS(TWSR&0xF8)
BYTEbyEEWait;
//////////////////////////////////////////////////////////////////////////
//implementation
BOOLEEPStart(BYTEaddr,BOOLbWrite)
{
byEEWait=10;//90~100ms
poll_ack:
TwiStart();
while(!(TWCR&(1<
returnFALSE;
}
}
if((TWI_STATUS!=TW_START)&&(TWI_STATUS!=TW_REP_START))
gotopoll_ack;
//byEEWait=3;//20~30ms
//sendSLA+R/W
TWDR=addr|bWrite;
TWCR=(1<
TwiStop();
returnFALSE;
}
}
if(EEWR==bWrite){//MTmode
//if(TWI_STATUS!=TW_MT_SLA_ACK)
switch(TWI_STATUS){
caseTW_MT_SLA_ACK:
break;
caseTW_MT_SLA_NACK:
gotopoll_ack;
default:
TwiStop();
returnFALSE;
}
}else{//MRmode
if(TWI_STATUS!=TW_MR_SLA_ACK)
returnFALSE;
}
returnTRUE;
}
//////////////////////////////////////////////////////////////////////
//
BYTEEEPWrite(WORDuiAddress,WORDuiLen,void*pBuf)//using0
{
unsignedinti,j,uICnt;
if(uiLen==0)return0;
uiCnt=0;
//uiEnd=uiAddress+uiLen;
i=uiAddress;
do{
if(!EEPStart(0xA0|EEADDR,EEWR)){//PollAck()isbuilt-in
return0;
}
TWDR=(BYTE)((i>>8)&0x00ff);//MSBofaddress
TWCR=(1<
while(!(TWCR&(1<
returnFALSE;
}
if(TWI_STATUS!=TW_MT_DATA_ACK){
returnFALSE;
}
TWDR=(BYTE)(i&0x00ff);//LSBofaddress
TWCR=(1<
while(!(TWCR&(1<
returnFALSE;
}
if(TWI_STATUS!=TW_MT_DATA_ACK)
returnFALSE;
//writedata
for(j=0;j<32;j++){
TWDR=((BYTE*)pBuf)[uiCnt];
TWCR=(1<
while(!(TWCR&(1<
returnFALSE;
}
if(TWI_STATUS!=TW_MT_DATA_ACK){
returnFALSE;
}
i++;
uiCnt++;
if((0==i%32)||(uiCnt==uiLen)){
TwiStop();
break;
}
}
}while(uiCnt
return1;
}
//////////////////////////////////////////////////////////////////////
//
BYTEEEPRead(WORDuiAddress,WORDuiLen,void*pBuf)
{
UINTi;
if(uiLen==0)return0;
if(!EEPStart(0xA0|EEADDR,EEWR)){//PollAck()isbuilt-in
return0;//↑
}//notRDbutwritedeviceaddresstotheChip
TWDR=(BYTE)((uiAddress>>8)&0x00ff);//((BYTE*)(&uiAddress))[1];//MSBofaddress
TWCR=(1<
while(!(TWCR&(1<
returnFALSE;
}
if(TWI_STATUS!=TW_MT_DATA_ACK)
returnFALSE;
TWDR=(BYTE)(uiAddress&0x00ff);//((BYTE*)(&uiAddress))[0];//LSBofaddress
TWCR=(1<
while(!(TWCR&(1<
returnFALSE;
}
if(TWI_STATUS!=TW_MT_DATA_ACK)
returnFALSE;
if(!EEPStart(0xA0+EEADDR,EERD)){//PollAck()){
return0;//↑
}//???howtoread?
for(i=0;i
byEEWait=3;//20~30ms
while(!(TWCR&(1<
returnFALSE;
}
if(TWI_STATUS!=TW_MR_DATA_ACK)
returnFALSE;
((BYTE*)pBuf)[i]=TWDR;//EEInByte();
}
TWCR=_BV(TWINT)|_BV(TWEN);//sendNACKtoinDICatefinalbyte
byEEWait=3;//20~30ms
while(!(TWCR&(1<
returnFALSE;
}
//if(TWI_STATUS!=TW_MR_DATA_ACK)
//returnFALSE;
((BYTE*)pBuf)[i]=TWDR;
TwiStop();
return1;
}