新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計(jì)應(yīng)用 > 單片機(jī)·實(shí)時(shí)時(shí)鐘DS1302

單片機(jī)·實(shí)時(shí)時(shí)鐘DS1302

作者: 時(shí)間:2016-11-24 來源:網(wǎng)絡(luò) 收藏

實(shí)驗(yàn)二:將實(shí)驗(yàn)一的時(shí)鐘程序,在LCD1602上顯示
程序:
main.h
# ifndef _MAIN_H_
# define _MAIN_H_
# include
# include
sbit SCK = P3^5 ;
sbit SDA = P3^4 ;
sbit RST = P1^7 ;
sbit RS = P1^0 ;
sbit RW = P1^1 ;
sbit EN = P1^5 ;
sbit BUSY = P0^7 ;
typedef unsigned char uint8 ;
typedef unsigned int uint16 ;
uint8 time[7]={50,59,23,15,8,7,10} ;
# define ds1302_w_addr 0x80
# define ds1302_r_addr 0x81
# endif
main.c
# include "main.h"
void write_ds1302_byte(uint8 dat)
{
uint8 i ;
for(i=0; i<8; i++)
{
SDA = dat&0x01 ;
dat>>=1 ;
SCK = 1 ;
SCK = 0 ;
}
}
uint8 read_ds1302_byte(void)
{
uint8 i, dat = 0 ;
for(i=0; i<8; i++)
{
dat>>=1 ;
if(SDA)
dat |= 0x80 ;
SCK = 1 ;
SCK = 0 ;
}
return dat ;
}
void reset_ds1302(void)
{
RST = 0 ;
SDA = 0 ;
RST = 1 ;
}
void clear_ds1302_wp(void)
{
reset_ds1302() ;
RST = 1 ;
write_ds1302_byte(0x8E) ;
write_ds1302_byte(0) ;
SDA = 0 ;
RST = 0 ;
}
void set_ds1302_wp(void)
{
reset_ds1302() ;
RST = 1 ;
write_ds1302_byte(0x8E) ;
write_ds1302_byte(0x80) ;
SDA = 0 ;
RST = 0 ;
}
void write_ds1302(uint8 addr,uint8 dat)
{
reset_ds1302() ;
RST = 1 ;
write_ds1302_byte(addr) ;
write_ds1302_byte(dat) ;
SDA = 0 ;
RST = 0 ;
}
uint8 read_ds1302(uint8 addr)
{
uint8 temp = 0 ;
reset_ds1302() ;
RST = 1 ;
write_ds1302_byte(addr) ;
temp =read_ds1302_byte() ;
SDA = 0 ;
RST = 0 ;
return temp ;
}
void set_time(uint8 *timedata)
{
uint8 i, tmp ;
for(i=0; i<7; i++)
{
tmp = timedata[i]/10 ;
timedata[i] = timedata[i] ;
timedata[i] = tmp*16 + timedata[i] ;
}
tmp = ds1302_w_addr ;
clear_ds1302_wp() ;
for(i=0; i<7; i++)
{
write_ds1302(tmp,timedata[i]) ;
tmp+=2 ;
}
set_ds1302_wp() ;
}
void read_time(uint8 *timedata)
{
uint8 temp, i ;
temp = ds1302_r_addr ;
for(i=0; i<7; i++)
{
timedata[i] = read_ds1302(temp) ;
temp+= 2 ;
}
}
void wait(void)
{
P0 = 0xFF ;
while(BUSY)
{
RS = 0 ;
RW = 1 ;
EN = 0 ;
EN = 1 ;
}
EN = 0 ;
}
void w_dat(uint8 dat)
{
wait() ;
EN = 0 ;
P0 = dat ;
RS = 1 ;
RW = 0 ;
EN = 1 ;
EN = 0 ;
}
void w_cmd(uint8 cmd)
{
wait() ;
EN = 0 ;
P0 = cmd ;
RS = 0 ;
RW = 0 ;
EN = 1 ;
EN = 0 ;
}
void w_hexnum(uint8 dat)
{
w_dat(dat/16 + 0) ; //這里注意/16,輸出為8421BCD碼,需要轉(zhuǎn)換
w_dat(dat + 0) ;
}
void Init_LCD1602(void)
{
w_cmd(0x38) ;
w_cmd(0x0c) ;
w_cmd(0x06) ;
w_cmd(0x01) ;
}
void main(void)
{
Init_LCD1602() ;
set_time(&time) ;
while(1)
{
read_time(&time) ; //指針的概念
w_cmd(0x80) ;
w_hexnum(time[6]) ;
w_dat(-) ;
w_hexnum(time[4]) ;
w_dat(-) ;
w_hexnum(time[3]) ;
w_cmd(0xC0) ;
w_hexnum(time[2]) ;
w_dat(:) ;
w_hexnum(time[1]) ;
w_dat(:) ;
w_hexnum(time[0]) ;
}
}

上一頁 1 2 下一頁

評論


技術(shù)專區(qū)

關(guān)閉