定时器实现秒表,每一秒写入24C02C一次,秒数可以用液晶1602第一行显示。显示格式为“miaoshu:**”,其中**代表具体的秒数。重新上电后,从上一次写入的秒数开始计时。下面我自己写的,读和写都没有显示出来
#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit sda=P3^1;
sbit scl=P3^0;
sbit dx=P2^6;
sbit wx=P2^7;
uchar sec,tcnt;
uchar code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
void delay()
{;;}
void delayms(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void start()
{
sda=1;
delay();
scl=1;
delay();
sda=0;
delay();
}
void stop()
{
sda=0;
delay();
scl=1;
delay();
sda=1;
delay();
}
void respons()
{
uchar i;
scl=1;
delay();
while((sda==1)&&(i<250))i++;
scl=0;
delay();
}
void init()
{
sda=1;
delay();
scl=1;
delay();
}
void write_byte(uchar date)
{
uchar i,temp;
temp=date;
for(i=0;i<8;i++)
{
temp=temp<<1;
scl=0;
delay();
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;
scl=0;
delay();
}
return k;
}
void write_add(uchar address,uchar date)
{
start();
write_byte(0xa0);
respons();
write_byte(address);
respons();
write_byte(date);
respons();
stop();
}
uchar read_add(uchar address)
{
uchar date;
start();
write_byte(0xa0);
respons();
write_byte(address);
respons();
start();
write_byte(0xa1);
respons();
date=read_byte();
stop();
return date;
}
void display(uchar shi,uchar ge)
{
P0=0xff;
delayms(1);
wx=1;
P0=0xfe;
wx=0;
P0=0xff;
delayms(1);
dx=1;
P0=table[shi];
dx=0;
P0=0xff;
delayms(1);
wx=1;
P0=0xfd;
wx=0;
P0=0xff;
delayms(1);
dx=1;
P0=table[ge];
dx=0;
}
void main()
{
init();
sec=read_add(1);
if(sec>60)sec=0;
TMOD=0x01;
ET0=1;
EA=1;
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
TR0=1;
while(1)
{
display(sec/10,sec%10);
if(tcnt==20)
{
write_add(1,sec);
tcnt=0;
sec++;
if(sec==60)
sec=0;
}
}
}
void t0()interrupt 1
{
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
tcnt++;
}
|