AT240C02中EEPROM保存數(shù)據(jù)
程序功能:
利用定時器產(chǎn)生一個0~99秒變化的秒表,并且顯示在數(shù)碼管上,
每過一秒將這個變化的數(shù)寫入板上AT24C02內(nèi)部。當(dāng)關(guān)閉電源,
并再次打開電源時,單片機(jī)先從AT24C02中將原來寫入的數(shù)讀取出來,
接著此數(shù)繼續(xù)變化并顯示在數(shù)碼管上。
************************/
/************************
CODE:
************************/
#include
#define uint unsigned int
#define uchar unsigned char
#define AT024C02 0xa0
sbit sda=P2^0;
sbit scl=P2^1;
sbit LS138A=P2^2;
sbit LS138B=P2^3;
sbit LS138C=P2^4;
uchar led[8];
uchar code dutable[]={
0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f};//段選
uchar sec,count;
/***********************
I2C總線控制
***********************/
void delay()
{;;}
void delay_1ms(uint z)
{
uint x,y;
for(x=z;x>0;x--)
{
for(y=0;y<=110;y++)
{
}
}
}
void i2cinit()
{
sda=1;
delay();
scl=1;
delay();
}
void start()
{
sda=1;
delay();
scl=1;
delay();
sda=0;
}
void stop()
{
sda=0;
delay();
scl=1;
delay();
sda=1;
}
void respons()
{
uchar i=0;
scl=1;
delay();
while((sda==1)&&(i<250))//等待應(yīng)答信號
{
i++;
}
scl=0;
delay();
}
void write_byte(uchar date)
{
uchar i,temp;
temp=date;
for(i=0;i<8;i++)
{
scl=0;
delay();
temp=temp<<1;
sda=CY;
delay();
scl=1;
delay();
}
scl=0;
delay();
sda=1;
delay();
}
uchar read_byte()
{
uchar i,k;
scl=0;
delay();
sda=1;
delay();
for(i=0;i<8;i++)
{
scl=1;
delay();
k=(k<<1)|sda;
delay();
scl=0;
delay();
}
scl=0;
delay();
sda=1;
delay();
return k;
}
void write_address(uchar address,uchar date)
{
start();
write_byte(AT024C02);
respons();
write_byte(address);
respons();
write_byte(date);
respons();
stop();
}
uchar read_address(uchar address)
{
uchar date;
start();
write_byte(AT024C02);
respons();
write_byte(address);
respons();
start();
write_byte(AT024C02+1);
respons();
date=read_byte();
stop();
return date;
}
/***********************
定時器中斷
***********************/
void time0uint()
{
sec=0;
count=0;
TMOD=0x01;
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
EA=1;
ET0=1;
TR0=1;
}
void display()
{
uchar i;
sec=read_address(1);
led[0]=dutable[sec/1000];
led[1]=dutable[sec%1000/100];
led[2]=dutable[sec%100/10];
led[3]=dutable[sec%10];
for(i=0;i<4;i++)
{
P0=led[i];
switch(i)
{
case 0:LS138A=0; LS138B=0; LS138C=0; break;
case 1:LS138A=1; LS138B=0; LS138C=0; break;
case 2:LS138A=0; LS138B=1; LS138C=0; break;
case 3:LS138A=1; LS138B=1; LS138C=0; break;
}
delay_1ms(2);
}
P0=0X00;
}
void main()
{
i2cinit();
time0uint();
while(1)
{
display();
}
}
void time0() interrupt 1
{
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
count++;
if(count==20)
{
count=0;
sec++;
if(sec>=100)
{
sec=0;
}
write_address(1,sec);
}
}
評論