1. 用C语言编程,利用定时器产生一个0~99秒变化的秒表,并且显示在数码管上,每过一秒将这个变化写入实验板上AT24C02,当关闭实验板电源,并再次打开实验板电源时,单片机从AT24C02中将原来写入的数据读出来,接着继续变化在数码管上。
#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int
//=========全局变量区============================================
bit write; //写24C02的标志;
sbit sda;
sbit scl;
sbit high;
sbit mid;
sbit low;
uint code NumTable[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};//数字的编码
uchar sec,tcnt;
uchar code table[]={
0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71
};
//=========全局变量区结束============================================
/**
步骤
接线方式:
、P0接数码管J12,实现段选
、译码器和数码管位选输入短接,J15+J16
、本实验使用的晶振是12.000
**/
//========函数区============================================
void delay()
{;;}
void delay1ms(uint z)
{
uint x,y;
;x--)
;y--);
}
/**
延时
**/
void delay_1ms(uint x){
uint i=x;
uint j;
;--i){
;--j);
}
}
/**
在数码管上显示对应的值
**/
void display(uchar Num)
{
P0=NumTable[Num];
delay_1ms);
P0; //送完段选信号后,进行消影的处理
}
/**
位,并分解计数值
**/
void DisplayNumByOrder(uint Value){
low);
low);
low);
low);
low);
low);
low);
low);
}
void start() //开始信号
{
sda;
delay();
scl;
delay();
sda;
delay();
}
void stop() //停止
{
sda;
delay();
scl;
delay();
sda;
delay();
}
void respons() //应答
{
uchar i;
scl;
delay();
))i++;
scl;
delay();
}
void write_byte(uchar date)
{
uchar i,temp;
temp=date;
;i++)
{
temp;
scl;
delay();
sda=CY;
delay();
scl;
delay();
}
scl;
delay();
sda;
delay();
}
uchar read_byte()
{
uchar i,k;
scl;
delay();
sda;
delay();
;i++)
{
scl;
delay();
k)|sda;
scl;
delay();
}
return k;
}
void write_address(uchar address,uchar date)
{
start();
write_byte(0xa0);
respons();
write_byte(address);
respons();
write_byte(date);
respons();
stop();
}
uchar read_address(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 init()
{
sda;
delay();
scl;
delay();
sec); //读出保存的数据赋于sec
) //防止首次读取出错误数据
sec;
TMOD
ET0;
EA;
TH0;//对TH0 TL0赋值
TL0;//使定时器0.05秒中断一次
TR0; //开始计时
}
void main()
{
init();//初始化
)
{
DisplayNumByOrder(sec);
) //判断计时器是否计时一秒
{
write; //清零
write_address中写入数据sec
}
}
}
//========函数区结束============================================
//========中断函数区============================================
//定时中断服务函数
{
TH0;//对TH0 TL0赋值
TL0;//重装计数初值
tcnt++; //每过50ms tcnt加一
次(1秒)时
{
tcnt; //重新再计
sec++;
write; //1秒写一次24C02
秒,再从零开始计时
sec;
}
}
//========中断函数区结束============================================