#include #include
本文引用地址:https://www.eepw.com.cn/article/201611/320229.htm#define uchar unsigned char
#define uint unsigned int
//定义LCD1602的端口应用
#define RS_CLI PORTB&=~BIT(PB1)
#define RS_SEI PORTB|=BIT(PB1)
#define RW_CLI PORTB&=~BIT(PB2)
#define RW_SEI PORTB|=BIT(PB2)
#define EN_CLI PORTB&=~BIT(PB3)
#define EN_SEI PORTB|=BIT(PB3)
//定义DS1302数据端口
#define RST_CLI PORTC&=~BIT(PC4)
#define RST_SEI PORTC|=BIT(PC4)
#define RST_IN DDRC&=~BIT(PC4)
#define RST_OUT DDRC|=BIT(PC4)
#define SCLK_CLI PORTC&=~BIT(PC2)
#define SCLK_SEI PORTC|=BIT(PC2)
#define SCLK_IN DDRC&=~BIT(PC2)
#define SCLK_OUT DDRC|=BIT(PC2)
#define IO_CLI PORTC&=~BIT(PC3)
#define IO_SEI PORTC|=BIT(PC3)
#define IO_R PINC&BIT(PC3)
#define IO_IN DDRC&=~BIT(PC3)
#define IO_OUT DDRC|=BIT(PC3)
#define ds1302_sec_add0x80//秒数据地址
#define ds1302_min_add0x82//分数据地址
#define ds1302_hr_add0x84//时数据地址
#define ds1302_date_add0x86//日数据地址
#define ds1302_month_add0x88//月数据地址
#define ds1302_day_add0x8a//星期数据地址
#define ds1302_year_add0x8c//年数据地址
#define ds1302_control_add0x8e//控制数据地址
#define ds1302_charger_add0x90
#define ds1302_clkburst_add0xbe
unsigned char time_buf[8] = {0x20,0x09,0x04,0x28,0x17,0x13,0x00,0x02};
unsigned char time_buf1[8] = {0x20,0x10,0x04,0x12,0x23,0x18,0x22,0x00};
void DS1302_WriteByte(uchar addr,uchar data)
{
uchar i=0;
RST_SEI; //启动DS1302,进行写操作
IO_OUT; //定义数据口为输出模式
addr=addr&0xfe; //最低位为0表示写入。为1时表示读取
for(i=0;i<8;i++)
{
if(addr&0x01) //DS1320发送数据是先低位后高位,当传送第一位时与0x01相与,
{ //如果相等,表示传送的位为高电平,不等则为低电平,第一次送完第一次后ADDR左移一位准备传送第二位数据
IO_SEI; //如果相等表示传送的位为高电平,不等则为低电平,如此循环8次之后,要写入的数据就写完了
}
else
{
IO_CLI;
}
SCLK_SEI;
SCLK_CLI;
addr=addr>>1;
}
IO_OUT;
for(i=0;i<8;i++)
{
if(data&0x01)
{
IO_SEI;
}
else
{
IO_CLI;
}
SCLK_SEI;
SCLK_CLI;
data=data>>1;
}
RST_CLI;
}
uchar DS1302_ReadByte(uchar addr)
{
uchar temp=0,i=0;
RST_SEI;
IO_OUT;
addr=addr|0x01;
for(i=0;i<8;i++)
{
if(addr&0x01)
{
IO_SEI;
}
else
{
IO_CLI;
}
SCLK_SEI;
SCLK_CLI;
addr=addr>>1;
}
IO_IN;
for(i=0;i<8;i++)//读数据和写数据正好相反,手法相同;先判断读取到的值是高位还是低位,在经行保存
{
temp=temp>>1;//为下一次保存数据做准备先读低位后读高位
if(IO_R)//如果读取到的数据为高,则置高
{
temp|=0x80;
}
else//如果读取到的数据为低,则啦低
{
temp&=0x7f;
}
SCLK_SEI;
SCLK_CLI;
}
RST_CLI;
return temp;
}
void DS1302_Init(void)
{
RST_CLI;
SCLK_CLI;
RST_OUT;
SCLK_OUT;
}
void DS1302_WriteTime(void)
{
DS1302_WriteByte(ds1302_control_add,0x00);//当写保护寄存器的最高位为0 时允许数据写入寄存器,