|
发表于 2015-10-9 15:02:17
|
显示全部楼层
#include"main.h"
#define pcf_read_add 0xa3
#define pcf_write_add 0xa2
#define changeHexToInt(hex) ( ( ((hex)>>4) *10 ) + ((hex)%16) )
#define changeIntToHex(dec) ( ( ((dec)/10) <<4 ) + ((dec)%10) )
//时间结构体
struct pcf_MDY{
unsigned char second;
unsigned char muite;
unsigned char hour;
unsigned char day;
unsigned char weelk;
unsigned char month;
unsigned char year;
};
unsigned char now_time[7]={0,0,0,21,22,17,0};
void set_real_time(void)//出口
{
unsigned char i;
for(i=0;i<6;i++)
{
now_time[i]=changeIntToHex(now_time[i]);
}
pcf_write_time();
}
void read_real_time(void)//出口
{
unsigned char i;
TWSR=0x00;
TWBR=0x72;
TWAR=0x00;
pcf_read_time();
for(i=0;i<6;i++)
{
now_time[i]=changeHexToInt(now_time[i]);
}
}
void pcf_start(void)
{
TWCR=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
while(!(TWCR&(1<<TWINT)));
}
void pcf_stop(void)
{
TWCR=(1<<TWINT)|(1<<TWEN)|(1<<TWSTO);
}
unsigned char pcf_read(unsigned char f)
{
unsigned char vibale;
if(f)
TWCR=(1<<TWINT)|(1<<TWEA)|(1<<TWEN);
else
TWCR=(1<<TWINT)|(1<<TWEN);
while(!(TWCR&(1<<TWINT)));
vibale=TWDR;
return vibale;
}
void pcf_write(unsigned char write)
{
TWDR=write;
TWCR=(1<<TWINT)|(1<<TWEN);
while(!(TWCR&(1<<TWINT)));
}
void pcf_read_time(void)
{
pcf_start();
pcf_write(pcf_write_add);
pcf_write(0X02); //写字节地址,秒地址
pcf_start();
pcf_write(pcf_read_add);
now_time[5]=pcf_read(1)&0x7f;//秒
now_time[4]=pcf_read(1)&0x7f;//分
now_time[3]=pcf_read(1)&0x3f;//时
now_time[2]=pcf_read(1)&0x3f;//天
now_time[6]=pcf_read(1)&0x07;//周
now_time[1]=pcf_read(1)&0x1f;//月
now_time[0]=pcf_read(0);//年
pcf_stop();
}
void pcf_write_time(void)
{
pcf_start();
pcf_write(pcf_write_add);
pcf_write(0x02);
pcf_write(now_time[5]);//秒
pcf_write(now_time[4]);//分
pcf_write(now_time[3]);//时
pcf_write(now_time[2]);//天
pcf_write(now_time[6]);//周
pcf_write(now_time[1]);//月
pcf_write(now_time[0]);//年
pcf_stop();
}
void pcf_run(void)
{
pcf_start();
pcf_write(pcf_write_add);
pcf_write(0x00);
pcf_write(0x00);
pcf_write(0x00);
pcf_stop();
}
void pcf_disbale(void)
{
pcf_start();
pcf_write(pcf_write_add);
pcf_write(0x00);
pcf_write(0x20);
pcf_stop();
}
void pcf_init(void)
{
TWSR=0x00;
TWBR=0x72;
TWAR=0x00;
delay_ms(10);
pcf_run();
delay_ms(10);
}
void SET_TIME_HANDDLE(void)
{
HOUR=22;
MIN=18;
SEC=0;
set_real_time();
}
MEGA48上跑过的,8M时钟,绝对能用。 |
|