C语言编写程序:利用定时器产生一个0~99秒变化的秒针,显示在数码管上,每过一秒将变化的数写入AT24c02内部,关闭电源再打开时单片机从AT24c02中将原来写入的数读出来,接着此数继续变化并显示在数码管上。
谢谢
我写的程序如下:
#include <reg52.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
#define Nop() _nop_()
sbit sda=P1^2; //数据线
sbit scl=P1^1; //时钟线
sbit wp=P1^0; //读写保护
uint num1,num,jia;
uchar code table[]={
0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x98};
uchar write;
void delay() //时序延时
{ _nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
void init() //初始化
{
sda=1;
delay();
scl=1;
delay();
}
void start() //启动
{
sda=1;
delay();
scl=1;
delay();
sda=0;
delay();
}
void stop() //停止
{
sda=0;
delay();
scl=1;
delay();
sda=1;
delay();
}
void writebyte(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();
}
void respons() //应答
{
uchar m;
m=0;
scl=1;
delay();
while((sda==1)&&(m<250))m++;
scl=0;
delay();
} //读数据
uchar readbyte()
{
uchar j,k;
scl=0;
delay();
sda=1;
delay();
for(j=0;j<8;j++)
{
scl=1;
delay();
k=(k<<1)|sda;
delay();
scl=0;
delay();
}
return k;
}
void writeadd(uchar address,uchar date)
{ // wp=0;
start();
writebyte(0xa0);
respons();
writebyte(address);
respons();
writebyte(date);
respons();
stop();
}
uchar readadd(uchar address)
{
uchar n;
start();
writebyte(0xa0); //寻址 、控制字节
respons(); //应答
writebyte(address); //把要读的首地址发送到从机?
respons();
start();
writebyte(0xa1); //再次发送寻址、控制字节
respons();
n=readbyte(); //读的字节数
stop();
return n;
}
void delayms(uchar shu) //数码管显示延时
{
uchar x,y;
for(x=shu;x>0;x--)
for(y=100;y>0;y--);
}
void display(uchar shi,uchar ge) //数码管显示
{
//int baochi=10;
//while(baochi--)
P2=0xff;
P2=0xfe;
P0=table[ge];
delayms(5);
P2=0xfd;
P0=table[shi];
delayms(5);
}
void main()
{
uchar num2;
init();
num=readadd(jia); //???
if(num>100)
num=0;
TMOD=0x10;
ET1=1;
EA=1;
TH1=(65536-50000)/256;
TL1=(65536-50000)%256;
TR1=1;
while(1)
{
display(num/10,num%10);
if(write==1)
{
write=0;
num2=num;
writeadd(jia,num2);
}
}
}
void timer1() interrupt 3
{
TH1=(65536-50000)/256;
TL1=(65536-50000)%256;
num1++;
if(num1==20)
{
num1=0;
jia++;
num++;
write=1;
if(num==100)
num=0;
}
} |