AT24C02EEPROM芯片《實(shí)現(xiàn)對(duì)其讀和寫(xiě)》
unsigned char readbyte() //讀一個(gè)字節(jié)
{
unsigned char i,j,k=0;
scl=0; nop(); sda=1;
for (i=0;i<8;i++)
{
nop(); scl=1; nop();
if(sda==1)
j=1;
else
j=0;
k=(k<<1)|j;
scl=0;
}
nop();
return(k);
}
void clock() //I2C總線(xiàn)時(shí)鐘
{
unsigned char i=0;
scl=1;
nop();
while((sda==1)&&(i<255))
i++;
scl=0;
nop();
}
////////從24c02的地址address中讀取一個(gè)字節(jié)數(shù)據(jù)/////
unsigned char read24c02(unsigned char address)
{
unsigned char i;
start();
writebyte(0xa0);
clock();
writebyte(address);
clock();
start();
writebyte(0xa1);
clock();
i=readbyte();
stop();
delay1(10);
return(i);
}
//////向24c02的address地址中寫(xiě)入一字節(jié)數(shù)據(jù)info/////
void write24c02(unsigned char address,unsigned char info)
{
EA=0;
start();
writebyte(0xa0);
clock();
writebyte(address);
clock();
writebyte(info);
clock();
stop();
EA=1;
delay1(50);
}
void main()
{
unsigned char i;
TMOD=0x01; //定時(shí)器工作在方式1
ET0=1;
EA=1;
TH0=0x4c; //對(duì)TH0 TL0賦值
TL0=0x00; //使定時(shí)器0.05秒中斷一次
TR0=1; //開(kāi)始計(jì)時(shí)
init(); //初始化24C02
sec=read24c02(1);//每次重新開(kāi)機(jī)時(shí),讀出保存的數(shù)據(jù)賦于sec
while(1)
{
i=20;
//num=read24c02(1);//讀出保存的數(shù)據(jù)賦于num
while(i--)
{
display(sec/10,sec%10);
}
if(write==1) //判斷計(jì)時(shí)器是否計(jì)時(shí)一秒
{
write=0; //清零
write24c02(1,sec); //在24c02的地址1中寫(xiě)入數(shù)據(jù)sec
}
}
}
void timer0(void) interrupt 1 using 0 //定時(shí)中斷服務(wù)函數(shù)
{
TH0=0x4c; //對(duì)TH0 TL0賦值 ,每隔0.05s發(fā)出一次中斷。
TL0=0x00; //重裝計(jì)數(shù)初值
times++; //每過(guò)250ust tcnt加一
if(times==20) //計(jì)滿(mǎn)20次(1秒)時(shí)
{
times=0; //重新再計(jì)
sec++;
write=1; //1秒寫(xiě)一次24C08
if(sec==60) //定時(shí)100秒,在從零開(kāi)始計(jì)時(shí)
{sec=0;}
}
}
評(píng)論