51单片机数码管万年历代码
时间: 2023-07-02 22:22:21 浏览: 176
以下是一个简单的51单片机数码管万年历的代码,仅供参考:
```
#include<reg52.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit DULA=P2^6;
sbit WELA=P2^7;
uchar code table[]={
0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f, //0~9的数码管编码
0x77,0x7c,0x39,0x5e,0x79,0x71,0x00 //A~F的数码管编码
};
uint year,month,day,week,hour,minute,second;
void delay(uint x)
{
uint i,j;
for(i=x;i>0;i--)
for(j=114;j>0;j--);
}
void display(uchar addr,uchar dat)
{
WELA=1;
P0=addr;
WELA=0;
P0=dat;
WELA=1;
}
void init_ds1302()
{
uchar i;
RST=0;
delay(1);
SCLK=0;
delay(1);
RST=1;
delay(1);
ds_write_byte(0x8e,0x00); //关闭写保护
for(i=0;i<8;i++)
{
ds_write_byte(0x80+i,(uchar)table[0]); //初始化RAM,清零
}
}
uchar ds_read_byte()
{
uchar i,j,byte=0;
for(i=0;i<8;i++)
{
SCLK=0;
byte>>=1;
if(DSIO)
{
byte|=0x80;
}
SCLK=1;
}
return byte;
}
void ds_write_byte(uchar dat,uchar cmd)
{
uchar i;
SCLK=0;
for(i=0;i<8;i++)
{
DSIO=dat&0x01;
dat>>=1;
SCLK=1;
SCLK=0;
}
SCLK=0;
DSIO=cmd; //写入命令或数据
SCLK=1;
SCLK=0;
}
void read_time()
{
uchar i,temp;
ds_write_byte(0x8e,0x00); //关闭写保护
temp=ds_read_byte();
ds_write_byte(0x8e,0x80); //打开写保护
year=ds_read_byte();
month=ds_read_byte();
week=ds_read_byte();
day=ds_read_byte();
hour=ds_read_byte();
minute=ds_read_byte();
second=ds_read_byte();
}
void write_time()
{
ds_write_byte(0x8e,0x00); //关闭写保护
ds_write_byte(0x80,0x00); //选择年
ds_write_byte(year,0x80); //写入年
ds_write_byte(month,0x80); //写入月
ds_write_byte(week,0x80); //写入星期
ds_write_byte(day,0x80); //写入日
ds_write_byte(hour,0x80); //写入小时
ds_write_byte(minute,0x80); //写入分钟
ds_write_byte(second,0x80); //写入秒钟
ds_write_byte(0x8e,0x80); //打开写保护
}
void display_time()
{
uchar a,b,c,d;
a=hour/10;
b=hour%10;
c=minute/10;
d=minute%10;
display(0x01,table[a]);
display(0x02,table[b]);
display(0x03,table[c]);
display(0x04,table[d]);
}
void main()
{
init_ds1302();
while(1)
{
read_time();
display_time();
write_time();
delay(1000);
}
}
```
注:该代码仅实现了时间的显示和更新功能,如需添加其他功能,需要根据实际需求自行修改。
阅读全文