上一章-蓝桥杯STC基础代码-串口通信
时钟芯片-DS1302
时钟芯片在比赛的时候使用基本没有什么难度,利用好主办方给的函数
void Write_Ds1302_Byte(unsigned char temp) ;
void Write_Ds1302( unsigned char address,unsigned char dat ) ;
unsigned char Read_Ds1302 ( unsigned char address );
配置过程
一般来说,我们只需要配置 时 分 秒 这三个就可以了。
写数据
根据芯片手册上的寄存器。
可以看到 秒 - 0x80 ,分 - 0x82 ,秒 -0x84
在写入寄存器的时候要把数据分成 个位跟十位 ,分别写进寄存器的低位跟高位。
注意
在写入数据之前要关闭写保护。
写完之后要打开写保护。
void Set_time(u8 hour, u8 min ,u8 sec)
{
u8 temp;
Write_Ds1302(0x8e,0);
temp = ( hour / 10 ) << 4 | hour% 10;
Write_Ds1302(0x84,temp);
temp = ( min / 10 ) << 4 | min% 10;
Write_Ds1302(0x82,temp);
temp = ( sec / 10 ) << 4 | sec% 10;
Write_Ds1302(0x80,temp);
Write_Ds1302(0x8e,0x80);
}
寄存器记不住没关系,打开芯片手册一查就好了。
读数据
在程序初始化的时候我们就把我们设定的时间写入,之后需要用到时间就读一下就好了。
在这里,我用三个全局变量来存储时间。
u8 d_hour,d_min,d_sec;
然后我们回到芯片手册的寄存器
可以看到读数据的话
秒-0x81,分-0x83,时-0x85
然后要注意的是读取之后还要对读取到的数据进行处理。
跟写数据一样,我们读到的数据 十位对应高四位 ,个位对应低四位。
代码如下
u8 d_hour,d_min,d_sec;
void Read_time(void)
{
u8 temp;
temp = Read_Ds1302(0x81);
d_sec = (temp >> 4 ) *10 + (temp & 0x0f);
temp = Read_Ds1302(0x83);
d_min = (temp >> 4 ) *10 + (temp & 0x0f);
temp = Read_Ds1302(0x85);
d_hour = (temp >> 4 ) *10 + (temp & 0x0f);
}