基于51单片机电子时钟代码
时间: 2023-12-12 18:01:59 浏览: 88
很抱歉,我无法提供基于51单片机的电子时钟代码。不过,你可以在网上搜索相关资源,或者自己编写代码。以下是一个简单的51单片机电子时钟代码示例,希望对你有所帮助:
```
#include<reg52.h>
sbit D1=P2^0;
sbit D2=P2^1;
sbit D3=P2^2;
sbit D4=P2^3;
sbit SDA=P1^0;
sbit SCL=P1^1;
unsigned char code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};//共阴极数码管0~9编码
unsigned char second=0;//秒
unsigned char minute=0;//分
unsigned char hour=0;//时
void delay_us(unsigned int n)
{
while(n--);
}
void delay_ms(unsigned int n)
{
while(n--)
{
delay_us(1000);
}
}
void write_DS1302_byte(unsigned char dat)//写入一个字节
{
unsigned char i;
for(i=0;i<8;i++)
{
SDA=dat&0x01;
dat>>=1;
SCL=1;
delay_us(5);
SCL=0;
delay_us(5);
}
}
unsigned char read_DS1302_byte()//读取一个字节
{
unsigned char i,dat=0;
for(i=0;i<8;i++)
{
dat>>=1;
if(SDA)
{
dat|=0x80;
}
SCL=1;
delay_us(5);
SCL=0;
delay_us(5);
}
return dat;
}
void write_DS1302(unsigned char reg, unsigned char dat)//写入DS1302寄存器
{
SCL=0;
delay_us(5);
SDA=0;
delay_us(5);
SCL=1;
delay_us(5);
SDA=0;
delay_us(5);
write_DS1302_byte(reg);
write_DS1302_byte(dat);
SDA=1;
delay_us(5);
SCL=0;
}
unsigned char read_DS1302(unsigned char reg)//读取DS1302寄存器
{
unsigned char dat;
SCL=0;
delay_us(5);
SDA=0;
delay_us(5);
SCL=1;
delay_us(5);
SDA=0;
delay_us(5);
write_DS1302_byte(reg);
SDA=1;
delay_us(5);
SCL=0;
delay_us(5);
SDA=0;
delay_us(5);
SCL=1;
delay_us(5);
dat=read_DS1302_byte();
SDA=1;
delay_us(5);
SCL=0;
return dat;
}
void init_DS1302()//初始化DS1302
{
write_DS1302(0x8e,0x00);//禁止写保护
write_DS1302(0x80,0x00);//秒清零
write_DS1302(0x82,0x00);//分清零
write_DS1302(0x84,0x00);//时清零
write_DS1302(0x86,0x01);//日设为星期一
write_DS1302(0x88,0x01);//月清零
write_DS1302(0x8c,0x00);//启用写保护
}
void display_time()//显示时间
{
D4=1;
D3=1;
D2=1;
D1=1;
if(hour<10)//显示小时
{
D3=0;
write_DS1302(0x84,0x80|(table[hour%10]));
}
else
{
D3=0;
write_DS1302(0x84,table[hour%10]);
D2=0;
write_DS1302(0x84+1,table[hour/10]);
}
D3=1;
if(minute<10)//显示分钟
{
D1=0;
write_DS1302(0x82,0x80|(table[minute%10]));
}
else
{
D1=0;
write_DS1302(0x82,table[minute%10]);
D4=0;
write_DS1302(0x82+1,table[minute/10]);
}
D1=1;
if(second%2==0)//显示秒
{
write_DS1302(0x80,table[second/10]);
D2=0;
write_DS1302(0x80+1,table[second%10]);
}
else
{
write_DS1302(0x80,0x00);
write_DS1302(0x80+1,0x00);
}
}
void main()
{
init_DS1302();//初始化DS1302
while(1)
{
second=read_DS1302(0x81);//获取秒
minute=read_DS1302(0x83);//获取分
hour=read_DS1302(0x85);//获取时
display_time();//显示时间
delay_ms(500);//延时500毫秒
}
}
```
阅读全文