SEI();
}
unsigned char EEPROM_read(unsigned int uiAddress)
{
while(EECR&(1< //判斷讀寫(xiě)忙標(biāo)志
CLI();
EEAR = uiAddress; //送入地址
EECR |=(1< //讀位置位
SEI();
return EEDR;//返回?cái)?shù)據(jù)
}
讀和寫(xiě)的操作如下面所示 讀寫(xiě)數(shù)據(jù)時(shí)要從0x01開(kāi)始 ,00地址有bug(數(shù)據(jù)手冊(cè)上講的)
temp=EEPROM_read(0x01);
EEPROM_write(0x01,temp);
二、提升篇-使用緩沖機(jī)構(gòu)的操作
思路是這樣的:首先建立讀寫(xiě)緩沖區(qū),把需要寫(xiě)的數(shù)據(jù)放入到寫(xiě)緩沖區(qū)中,由于在AVR單片機(jī)中,寫(xiě)一個(gè)數(shù)據(jù)時(shí)比較慢的大概要8ms吧,這么長(zhǎng)的時(shí)間肯定不能一直while等下去,因此我們用中斷在處理,等單片機(jī)EEPROM程序?qū)懞昧司陀衦eady中斷,這時(shí)就能讀寫(xiě)操作了,寫(xiě)的時(shí)候從寫(xiě)緩沖區(qū)中取出數(shù)據(jù),寫(xiě)的時(shí)候要注意不允許讀,經(jīng)過(guò)一段時(shí)間后就完成了,而且我們發(fā)現(xiàn)寫(xiě)的時(shí)候只是把數(shù)據(jù)送入到單片機(jī)中的一個(gè)寄存器中,至于EEPROM什么時(shí)候來(lái)讀這個(gè)寄存器直至寫(xiě)完,我們也沒(méi)有必要管他,因?yàn)樗僮骱昧藭?huì)中斷告訴我們,從而這8ms還可以用來(lái)執(zhí)行其它的程序了,就這樣直到所有的數(shù)據(jù)都寫(xiě)完了。
#pragma interrupt_handler vIvEeReady:iv_EE_READY
void vIvEeReady(void)
{
if(!fgEepromBufEmpty()) //緩沖區(qū)數(shù)據(jù)還沒(méi)完全寫(xiě)到EPPROM中
{
CLI(); //寫(xiě)的時(shí)候不希望有別的中斷
EEAR = _sEepromBuf[_bEepromBufRdPtr].wAddress;
EEDR = _sEepromBuf[_bEepromBufRdPtr].bVal; //數(shù)據(jù)寫(xiě)入
EECR |= BIT(EEMWE);
EECR |= BIT(EEWE);
SEI(); //寫(xiě)好這個(gè)就打開(kāi),盡可能滿足實(shí)時(shí)性
_bEepromBufRdPtr++; //指向下一個(gè)緩沖數(shù)據(jù)
if(_bEepromBufRdPtr >= EEPROM_WRITE_BUF_SIZE) //到了緩沖區(qū)頂了
{
_bEepromBufRdPtr = 0; //從頭部開(kāi)始計(jì)數(shù)
}
_bEepromBufNs--; //當(dāng)前還沒(méi)有寫(xiě)入EEPROM的數(shù)
}
else
{
EECR &= ~BIT(EERIE); //都寫(xiě)好了就把中斷關(guān)閉掉
}
}
uchar bWriteData2Eeprom(uint wAddress, uchar bVal)
{
if(fgEepromBufFull()) //是否達(dá)到緩沖定義的最大值
{
return RET_BUSY;
}
CLI(); //關(guān)中斷?這里應(yīng)該放在中斷函數(shù)里面的
_sEepromBuf[_bEepromBufWrPtr].wAddress = wAddress;
_sEepromBuf[_bEepromBufWrPtr].bVal = bVal;
_bEepromBufWrPtr++;
if(_bEepromBufWrPtr >= EEPROM_WRITE_BUF_SIZE) //寫(xiě)滿了就從頭開(kāi)始寫(xiě)
{ //需要保證數(shù)據(jù)不丟失
_bEepromBufWrPtr = 0;
}
_bEepromBufNs++; //寫(xiě)一個(gè)計(jì)數(shù)就加一下
EECR |= BIT(EERIE); //寫(xiě)一個(gè)數(shù)據(jù)后這里打開(kāi)了中斷
SEI();
return RET_SUCCESS;
}
// Notice! The programer must ensure the EEPROM is NOT in writing state.
uchar bReadDataFromEeprom(uint wAddress, uchar *pbVal)
{
if(EECR & BIT(EEWE)) //沒(méi)有在寫(xiě)時(shí)才能讀取,一般放在程序開(kāi)始時(shí)
{
return RET_BUSY;
}
EEAR = wAddress; //送入地址
EECR |= BIT(EERE); //讀鎖存
*pbVal = EEDR; //取出數(shù)據(jù)
return RET_SUCCESS; //讀取成功
}
BYTE bGetEepromWrBuf(void)
{
return _bEepromBufNs; //讀取當(dāng)前剩余的沒(méi)寫(xiě)入的數(shù)據(jù)
}
void bClrEepromBuf(void)
{
CLI();
_bEepromBufNs = 0;
_bEepromBufRdPtr = _bEepromBufWrPtr;
EECR &= ~BIT(EERIE);
SEI();
}
BOOL fgEepromWizard(void)
{
BOOL fgRet = FALSE;
return fgRet;
}
void vInitEeprom(void)
{
EECR = 0x00; //EEPROM控制寄存器清零
_bEepromBufWrPtr = 0; //讀寫(xiě)指針和數(shù)據(jù)計(jì)數(shù)清零
_bEepromBufRdPtr = 0;
_bEepromBufNs = 0;
}
評(píng)論