ds1302还有一个字节的充电标志位,备用电源为可充电电池可用
此外还有12小时和24小时制
0x84写入时,最高位写1,则切换12小时制
clock.h
clock.c
#ifndef __CLOCK_H__
#define __CLOCK_H__
#include<reg51.h>
sbit DS_IO = P1^0;
sbit DS_SCLK = P1^1;
sbit DS_RST = P1^2;
void ds1302_write(unsigned char dat);
unsigned char ds1302_read();
void ds1302_set(unsigned char addr,unsigned char dat);
unsigned char ds1302_get(unsigned char addr);
unsigned char bcd2decimal(unsigned char bcd);
unsigned char calc_week(unsigned char yy,unsigned char month,unsigned char day);
#endif
#include<reg51.h>
#include<intrins.h>
#include "clock.h"
#include "lcd.h"
unsigned char sec,min,hour,day,week,month,year;
unsigned int x;
void main(){
// ds1302_set(0x8E, 0x00);//关闭写保护,允许写入
// ds1302_set(0x80, 0x34);//写秒
// ds1302_set(0x82, 0x23);//写分
// ds1302_set(0x84, 0x15);//写时
// ds1302_set(0x8E, 0x80);//打开写保护,禁止写入
lcd_cmd(0x01);//清屏
lcd_cmd(0x06);//指针自增
lcd_cmd(0x0C);//显示开,光标关
lcd_cmd(0x38);//8位接口,两行显示
while(1){
sec = ds1302_get(0x81);//读秒
min = ds1302_get(0x83);//读分
hour = ds1302_get(0x85);//读时
day = ds1302_get(0x87);//读日
month = ds1302_get(0x89);//读月
week = ds1302_get(0x8b);//读周
year = ds1302_get(0x8d);//读年
lcd_dispos(0,0);//显示地址
lcd_dis("20");
lcd_write((year>>4) + 48);
lcd_write((year%16) + 48);
lcd_write('-');
lcd_write((month>>4) + 48);
lcd_write((month%16) + 48);
lcd_write('-');
lcd_write((day>>4) + 48);
lcd_write((day%16) + 48);
lcd_dispos(1,0);//显示地址
lcd_write((hour>>4) + 48);
lcd_write((hour%16) + 48);
lcd_write(':');
lcd_write((min>>4) + 48);
lcd_write((min%16) + 48);
lcd_write(':');
lcd_write((sec>>4) + 48);
lcd_write((sec%16) + 48);
lcd_dis(" wk ");
week += 47;
if(week == 48)
week += 7;
lcd_write(week);
x= 50000;
while(x--);
}
}
void ds1302_write(unsigned char dat){
unsigned char i;
for(i=0;i<8;i++){
DS_SCLK = 0;
_nop_();
DS_IO = dat & 0x01;
_nop_();
DS_SCLK = 1;
_nop_();
dat>>=1;
}
}
unsigned char ds1302_read(){
unsigned char i,dat;
for(i=0;i<8;i++){
dat>>=1;
DS_SCLK = 0;
_nop_();
if(DS_IO == 1) {
dat |= 0x80;
}
_nop_();
DS_SCLK = 1;
_nop_();
}
return dat;
}
void ds1302_set(unsigned char addr,unsigned char dat){
DS_RST = 0;
DS_SCLK = 0;
DS_RST = 1;
ds1302_write(addr);
ds1302_write(dat);
DS_RST = 0;
}
unsigned char ds1302_get(unsigned char addr){
unsigned char dat;
DS_RST = 0;
DS_SCLK = 0;
DS_RST = 1;
ds1302_write(addr);
dat = ds1302_read();
DS_RST = 0;
return dat;
}
unsigned char bcd2decimal(unsigned char bcd){
return bcd - (bcd>>3)*3;
}
unsigned char calc_week(unsigned char yy,unsigned char month,unsigned char day){
unsigned char week = 8;
unsigned int year;
year = 2000+yy;
if(month == 1 || month == 2){
month += 12;
year--;
}
week = (day+2*month+3*(month+1)/5+year+year/4-year/100+year/400)%7+1;
return week;
}
|