电子时钟
主函数
#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit dula = P2^6;
sbit wela = P2^7;
sbit sda = P2^0;
sbit scl = P2^1;
uchar cnt=0;
uchar time[]={0,0,0};
uchar code table[]={
0x3f,0x06,0x5b,
0x4f,0x66,0x6d,
0x7d,0x07,0x7f,0x6f
};
void Delay(uchar x)
{
uchar i,j;
for(i=x;i>0;i--)
for(j=110;j>0;j--);
}
void Display(uchar hour,uchar min ,uchar sec)
{
P0=0xfe;
wela=1;
wela=0;
P0=table[hour/10];
dula=1;
dula=0;
Delay(5);
P0=0xfd;
wela=1;
wela=0;
P0=table[hour%10];
dula=1;
dula=0;
Delay(5);
P0=0xfb;
wela=1;
wela=0;
P0=table[min/10];
dula=1;
dula=0;
Delay(5);
P0=0xf7;
wela=1;
wela=0;
P0=table[min%10];
dula=1;
dula=0;
Delay(5);
P0=0xef;
wela=1;
wela=0;
P0=table[sec/10];
dula=1;
dula=0;
Delay(5);
P0=0xdf;
wela=1;
wela=0;
P0=table[sec%10];
dula=1;
dula=0;
Delay(5);
}
void Init_time0()
{
TMOD=1;
TH0=(65536-45872)/256;
TL0=(65539-45872)%256;
EA=1;
ET0=1;
TR0=1;
}
void main()
{
Init_iic();
time[0]=read_24c02(1);
time[1]=read_24c02(2);
time[2]=read_24c02(3);
Init_time0();
while(1)
{
uchar i=10;
while(i--)
Display(time[2],time[1],time[0]);
}
}
void time0() interrupt 1
{
TH0=(65536-45872)/256;
TL0=(65539-45872)%256;
cnt++;
if(cnt==20)
{
cnt=0;
time[0]++;
write_24c02(1,time[0]);
}
if(time[0]==60)
{
time[0]=0;
write_24c02(1,time[0]);
time[1]++;
write_24c02(2,time[1]);
}
if(time[1]==60)
{
time[1]=0;
write_24c02(2,time[1]);
time[2]++;
write_24c02(3,time[2]);
}
if(time[2]==24)
{
time[2]=0;
write_24c02(3,time[2]);
}
}
i2c通信
void flash()
{;;}
void Init_iic()
{
scl=1;
flash();
sda=1;
flash();
}
void start_iic()
{
scl=1;
flash();
sda=1;
flash();
sda=0;
flash();
}
void stop_iic()
{
sda=0;
flash();
scl=1;
flash();
sda=1;
flash();
}
void input_iic(uchar j)
{
uchar i,temp;
temp = j;
for(i=0;i<8;i++)
{
temp = temp << 1;
scl=0;
flash();
sda=CY;
flash();
scl=1;
flash();
}
scl=0;
flash();
sda=1;
flash();
}
uchar output_iic()
{
uchar i,j,k=0;
scl=0;
flash();
sda=1;
flash();
for(i=0;i<8;i++)
{
scl=1;
flash();
j=sda;
k = (k<<1) | j;
scl=0;
flash();
}
flash();
return k;
}
void clock_iic()
{
uchar i=0;
scl=1;
flash();
while((sda==1)&&(i<250))
i++;
scl=0;
flash();
}
uchar read_24c02(uchar address)
{
uchar i;
start_iic();
input_iic(0xa0);
clock_iic();
input_iic(address);
clock_iic();
start_iic();
input_iic(0xa1);
clock_iic();
i=output_iic();
stop_iic();
return i;
}
void write_24c02(uchar address,uchar i)
{
start_iic();
input_iic(0xa0);
clock_iic();
input_iic(address);
clock_iic();
input_iic(i);
clock_iic();
Delay(1);
stop_iic();
}