#define DS1302_PORT PORTC
#define DS1302_DDR DDRC
#define DS1302_PIN PINC
#define SETBIT(x,y) (x|=(1<<y))
#define CLRBIT(x,y) (x&=(~(1<<y)))
#define CHKBIT(x,y) (x&(1<<y))
/************************************************************************/
/* 初始化 */
/************************************************************************/
//1302管脚初始化
void initialize_1302(void)
{
SETBIT(DS1302_PORT,T_CLK);
SETBIT(DS1302_PORT,T_IO);
SETBIT(DS1302_PORT,T_RST);
SETBIT(DS1302_DDR,T_CLK);
SETBIT(DS1302_DDR,T_IO);
SETBIT(DS1302_DDR,T_RST);
delay_nus(1);
write_1302(0x8e,0x00);
write_1302(0x90,0xA5);
write_1302(0x80,0x00);
}
//1302写一bit数据函数
void ds1302_write_a_byte(unsigned char ucDa)
{
unsigned char i;
for(i=8; i>0; i--)
{
CLRBIT(DS1302_PORT,T_CLK);
if (ucDa&1) SETBIT(DS1302_PORT,T_IO);
else CLRBIT(DS1302_PORT,T_IO);
SETBIT(DS1302_PORT,T_CLK);
ucDa>>=1;
}
}
//1302读一bit数据
unsigned char ds1302_read_a_byte(void)
{
unsigned char i,t=0;
CLRBIT(DS1302_DDR,T_IO);
CLRBIT(DS1302_PORT,T_IO);
for(i=8; i>0; i--)
{
t>>=1;
SETBIT(DS1302_PORT,T_CLK);
delay_nus(1);
CLRBIT(DS1302_PORT,T_CLK);
delay_nus(1);
if(CHKBIT(DS1302_PIN,T_IO))t|=0x80;
}
SETBIT(DS1302_DDR,T_IO);
return(t);
}
//往DS1302写入数据
void write_1302(unsigned char ucAddr, unsigned char ucDa)
{
CLRBIT(DS1302_PORT,T_RST); //T_RST=0
CLRBIT(DS1302_PORT,T_CLK); //T_CLK=0;
SETBIT(DS1302_PORT,T_RST); //T_RST=1
ds1302_write_a_byte(ucAddr); // 地址,命令
CLRBIT(DS1302_PORT,T_CLK);
ds1302_write_a_byte(ucDa); // 写1Byte数据
CLRBIT(DS1302_PORT,T_CLK); //T_CLK=1
CLRBIT(DS1302_PORT,T_RST); //T_RST=0
}
//读取DS1302某地址的数据
unsigned char read_1302(unsigned char ucAddr)
{
unsigned char ucDa;
CLRBIT(DS1302_PORT,T_RST);
CLRBIT(DS1302_PORT,T_CLK);
SETBIT(DS1302_PORT,T_RST);
ds1302_write_a_byte(ucAddr); // 地址,命令
ucDa = ds1302_read_a_byte(); // 读1Byte数据
CLRBIT(DS1302_PORT,T_CLK);
CLRBIT(DS1302_PORT,T_RST);
return(ucDa);
}
///写某一位的时钟/////////////////////////////////////////////
void v_Setdd1302(unsigned char ucAddr,unsigned char pSecDa) //写某一位的时钟
{
write_1302(0x8e,0x00); //控制命令,WP=0,写操作?
write_1302(ucAddr,pSecDa); //
write_1302(0x8e,0x80); // 控制命令,WP=1,写保护?
}
// 读取DS1302当前时间
void v_Get1302(unsigned char ucCurtime[])
{
unsigned char i;
unsigned char ucAddr = 0x81;
for (i=0;i<7;i++)
{
ucCurtime = read_1302(ucAddr); //格式为: 秒 分 时 日 月星期 年
ucAddr += 2;
}
CLRBIT(DS1302_PORT,T_CLK);
}
文章评论(0条评论)
登录后参与讨论