|
本人正在學習單片機,已超過2個月,此程序適合學習過單片機的新手借鑒和討論,注釋詳盡。
本程序不可通過按鍵設置時間,可按鍵設置時間的程序正在創作。詳細程序可下載附件。
- #include <reg52.h>
- #include"inc/lcd.h"
- #define uchar unsigned char
- #define uint unsigned int
- sbit IO = P3^6;
- sbit SCLK = P3^5;
- sbit RST = P3^7;
- sbit ACC_0 = ACC^0;//累加器第一位
- sbit ACC_7 = ACC^7;//累加器最后一位
- //寫的地址
- uchar code write_addr[7]=
- {0x80,0x82,0x84,0x86,0x88,0x8a,0x8c};
- //讀的地址
- uchar code read_addr[7]=
- {0x81,0x83,0x85,0x87,0x89,0x8b,0x8d};
- /*形式上為十六進,數值是BCD碼*/
- //存儲格式是BCD碼秒 分 時 日 月 周 年
- uchar
- time[7]={0x00,0x14,0x11,0x13,0x12,0x04,0x19};
- /*如果數值時間是十進制,寫入時間時要先轉化為BCD碼*/
- //uchar time[7]={0,25,15,15,12,6,18}; //十進制
- void write_byte(uchar dat)//寫一個字節
- {
- uchar i;
- ACC=dat;
- for(i=8;i>0;i--)
- {
- IO=ACC_0;
- SCLK=0;
- SCLK=1;
- ACC=ACC>>1;
- }
- /*
- uchar i;
- for(i=0;i<8;i++)
- {
- IO = (bit)(dat & 0x01);
- SCLK = 0;
- SCLK = 1;
- dat >>= 1;
- }
- */
- }
- uchar read_byte() //讀一個字節
- {
- uchar i;
-
- for(i=0;i<8;i++)
- {
- ACC_7=IO;
- SCLK=1;
- SCLK=0;
- ACC=ACC>>1;
- }
- IO=0;
- return (ACC);
- /*
- uchar dat,i;
- for(i=0;i<8;i++)
- {
-
- if(IO == 1)
- {
-
- dat = dat|0x80;
- }
- SCLK = 1;
- SCLK = 0;
- dat >>= 1;
- }
- IO = 0;
- return (dat);
- */
- }
- void write_1302(uchar add,uchar dat) //向1302芯片寫
- 函數,指定寫入地址,數據
- {
- RST=0;
- SCLK=0;
- RST=1;
- write_byte(add);
- write_byte(dat);
- SCLK=1;
- RST=0;
- }
- uchar read_1302(uchar add) //從1302
- 讀數據函數,指定讀取數據來源地址
- {
- uchar temp;
- RST=0;
- SCLK=0;
- RST=1;
- write_byte(add);
- temp=read_byte();
- SCLK=1;
- RST=0;
- return(temp);
- }
-
- void ds1302_init()
- {
- uchar k;
- write_1302(0x8e,0x00); //禁止寫保
- 護,即允許數據寫入
- for(k=0;k<7;k++) //寫入7個字節
- 的時鐘信號:分秒時日月周年
- {
- write_1302
- (write_addr[k],time[k]);
- }
- write_1302
- (0x8e,0x80); //打開寫保護
- /*//寫入時間時要先轉化為BCD碼
- uchar i,tmp;
- write_1302(0x8e,0x00); //禁止寫保護,即允許數
- 據寫入
- for (i=0; i<7; i++)
- {
- tmp = time[i] / 10;
- time[i] = time[i] % 10;
- time[i] = time[i] + tmp*16; // 十
- 進制轉化為BCD格式
- write_1302(write_addr[i],time[i]);
- //寫入7個字節的時鐘信號:分秒時日月周
- 年
- }
- write_1302(0x8e,0x80); //打開寫保護
- */
- }
- void BCD_STRING(uchar bcd, uchar *str) //BCD轉化為字符
- 串
- {
- *str = (bcd >> 4) + '0';
- *(str+1) = (bcd & 0x0f) + '0';
- }
- void read_time(uchar *timedata)
- {
- uchar n;
- for(n=0;n<7;n++)
- {
- timedata[n]=read_1302(read_addr[n]);
- //讀取分秒時日月周年
- }
- BCD_STRING(timedata[6], LCD_TIME+0);//轉化后年
- ,存放在LCD_TIME
- BCD_STRING(timedata[4], LCD_TIME+2);//轉化后月
- BCD_STRING(timedata[3], LCD_TIME+4);//轉化后日
- BCD_STRING(timedata[5], LCD_TIME+6);//轉化后周
- BCD_STRING(timedata[2], LCD_TIME+8);//轉化后時
- BCD_STRING(timedata[1], LCD_TIME+10);//轉化后
- 分
- BCD_STRING(timedata[0], LCD_TIME+12);//轉化后
- 秒
- }
- void main()
- {
- ds1302_init();//1302初始化,設定時間
- Lcd_init(); // lcd初始化
- while(1)
- {
- read_time(&time); //讀取時間
- lcd_dis(); // 顯示在lcd
- }
- }
復制代碼
|
|