程序功能:
利用定时器产生一个0~99秒变化的秒表,并且显示在数码管上,
每过一秒将这个变化的数写入板上AT24C02内部。当关闭电源,
并再次打开电源时,单片机先从AT24C02中将原来写入的数读取出来,
接着此数继续变化并显示在数码管上。
************************/
/************************
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))//等待应答信号
{
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);
}
}
上一篇:AT24C02EEPROM芯片《实现对其读和写》
下一篇:单片机中的掉电存储管理
推荐阅读最新更新时间:2024-03-16 14:03