ds1302时钟-AVR程序代码
扫描二维码
随时随地手机看文章
#include
#include"DS1302.h"
#include
voidds1302_init(void)
{
PORTX=0x00;
DDRX=0x07;
}
voidwrite_ds1302_byte(unsignedchardat)
{
unsignedchari;
for(i=0;i<8;i++)
{
SCK=0;
IO_out=dat&0x01;
dat=dat>>1;
SCK=1;
}
}
voidwrite_ds1302(unsignedcharadd,unsignedchardat)
{
RST=1;
delay_us(1);
write_ds1302_byte(add);
write_ds1302_byte(dat);
RST=0;
delay_us(2);
IO_out=0;
SCK=0;
}
unsignedcharread_ds1302(unsignedcharadd)
{
unsignedchari,value=0;
RST=1;
write_ds1302_byte(add);
IO_setting=0;
for(i=0;i<8;i++)
{
value=value>>1;
SCK=0;
SCK=0;//必须给两次!!
if(IO_in)value=value|0x80;
SCK=1;
}
IO_setting=1;
SCK=0;
RST=0;
delay_us(2);
IO_out=0;
returnvalue;
}
voidset_rtc(unsignedchar*time_data)
{
unsignedchari,j,write_add;
for(i=0;i<7;i++)
{
j=time_data[i]/10;
time_data[i]=time_data[i];
time_data[i]=time_data[i]+j*16;
}
write_ds1302(0x8e,0x00);//去除写保护
for(i=0,write_add=0x8c;i<7;i++,write_add-=2)
write_ds1302(write_add,time_data[i]);
write_ds1302(0x8e,0x80);
}
voidread_rtc(unsignedchar*time_data)
{
unsignedchari,j,read_add;
write_ds1302(0x8e,0x00);
for(i=0,read_add=0x8d;i<7;i++,read_add-=2)
time_data[i]=read_ds1302(read_add);
for(i=0;i<7;i++)
{
j=time_data[i]/16;
time_data[i]%=16;
time_data[i]+=j*10;
}
write_ds1302(0x8e,0x80);
}