DS1302 须要BCD处理
- #include "reg51.h"
- #define ds1302_sec_add 0x80 //秒数据地址
- #define ds1302_min_add 0x82 //分数据地址
- #define ds1302_hr_add 0x84 //时数据地址
- #define ds1302_date_add 0x86 //日数据地址
- #define ds1302_month_add 0x88 //月数据地址
- #define ds1302_day_add 0x8a //星期数据地址
- #define ds1302_year_add 0x8c //年数据地址
- #define ds1302_control_add 0x8e //控制数据地址
- #define ds1302_charger_add 0x90
- #define ds1302_clkburst_add 0xbe
- sbit RST= P3^5;
- sbit SCLK= P3^6;
- sbit DPIO= P3^4;
- unsigned char code READ_RTC_ADDR[7] = {0x81, 0x83, 0x85, 0x87, 0x89, 0x8b, 0x8d};
- unsigned char code WRITE_RTC_ADDR[7] = {0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c};
- unsigned char time[7];
- void delay()
- {
- unsigned char i;
- unsigned char j;
- for(i=0;i<6;i++)
- for(j=0;j<6;j++);
- }
- void sendbyte(unsigned char addr ,unsigned char dat)
- {
- unsigned char i;
- RST =0;
- delay();
- SCLK =0;
- delay() ;
- RST =1;
- delay();
- for(i=0;i<8;i++)
- {
- DPIO=addr&0x01;
- addr>>=1;
- SCLK =1;
- delay();
- SCLK =0;
- delay();
- }
- for(i=0;i<8;i++)
- {
- DPIO=dat&0x01;
- dat>>=1;
- delay();
- SCLK =1;
- delay();
- delay();
- SCLK =0;
- delay();
- }
- RST=0;
- delay();
- SCLK =0;
- delay();
- }
- unsigned char read(unsigned char addr)
- {
- unsigned char i;
- unsigned char dat;
- unsigned char tmp;
- RST =0;
- delay();
- SCLK =0;
- RST =1;
- delay();
- for(i=0;i<8;i++)
- {
- DPIO=addr&0x01;
- addr>>=1;
- SCLK =1;
- delay();
- SCLK =0;
- delay();
- }
- for(i=0;i<8;i++)
- {
- DPIO=tmp;
- dat|=tmp<<7;
- SCLK =1;
- delay();
- SCLK =0;
- delay();
- }
- RST=0;
- delay();
- SCLK =0;
- delay();
- DPIO = 0;
- delay();
- return dat;
- }
- void read_reg()
- {
- unsigned char i, tmp;
- unsigned char time_buf[8] ;
- for(i=0;i<8;i++)
- {
- time_buf[i]=read( READ_RTC_ADDR[i]);
- }
- for(i=0;i<8;i++)
- { //BCD处理
- tmp=time_buf[i]/16;
- time[i]=time_buf[i]%16;
- time[i]=time[i]+tmp*10;
- }
- }
- void write()
- {
- unsigned char i, tmp;
- unsigned char time_buf[8] ;
- sendbyte(0x8e,0x00);
- time[0]=0x30;
- time[1]=0x35;
- time[2]=0x20;
- time[3]=0x25;
- time[4]=0x05;
- time[5]=0x05;
- time[6]=0x18;
- for(i=0;i<7;i++)
- { //DS1302 须要BCD处理
- tmp=time[i]/10;
- time_buf[i]=time[i]%10;
- time_buf[i]=time_buf[i]+tmp*16;
- }
- for(i=0;i<7;i++)
- {
- sendbyte(WRITE_RTC_ADDR[i],time_buf[i]);
- delay();
- }
- sendbyte(0x8E, 0x80);
- }
- void uart_init(void)
- {
- // 波特率9600
- SCON = 0x50; // 串口工作在模式1(8位串口)、允许接收
- PCON = 0x00; // 波特率不加倍
- // 通信波特率相关的设置
- TMOD = 0x20; // 设置T1为模式2
- TH1 = 253;
- TL1 = 253; // 8位自动重装,意思就是TH1用完了之后下一个周期TL1会
- // 自动重装到TH1去
- TR1 = 1; // 开启T1让它开始工作
- }
- // 通过串口发送1个字节出去
- void uart_send_byte(unsigned char c)
- {
- // 第1步,发送一个字节
- SBUF = c;
- // 第2步,先确认串口发送部分没有在忙
- while (!TI);
- // 第3步,软件复位TI标志位
- TI = 0;
- }
- void main()
- {
- unsigned char k;
- uart_init();
- write();
-
- while(1)
- {
- read_reg();
- for(k=0;k<7;k++)
- {
- uart_send_byte(time[k]);
- }
- delay();
- }
- }
复制代码 |