- #define DS3231_WriteAddress 0xD0 //
- #define DS3231_ReadAddress 0xD1 //
- bit ack;
- void Delay6us(void) //@11.0592MHz
- {
- unsigned char i;
- i = 14;
- while (--i);
- }
- void Delay1us(void) //@11.0592MHz
- {
- _nop_();
- _nop_();
- _nop_();
- }
- void Start_I2C()
- {
- SDA=1;
- Delay1us();
- SCL=1;
- Delay6us();
- SDA=0;
- Delay6us();
- SCL=0;
- Delay1us();
- Delay1us();
- }
- void Stop_I2C()
- {
- SDA=0;
- Delay1us();
- SCL=1;
- Delay6us();
- SDA=1;
- Delay6us();
- }
- void SendByte(uchar c)
- {
- uchar BitCnt;
- for(BitCnt=0;BitCnt<8;BitCnt++)
- {
- if((c<<BitCnt)&0x80)
- SDA=1;
- else
- SDA=0;
- Delay1us();
- SCL=1;
- Delay6us();
- SCL=0;
- }
- Delay1us();
- SDA=1;
- Delay1us();
- SCL=1;
- Delay6us();
- if(SDA==1)
- ack=0;
- else
- ack=1;
- SCL=0;
- Delay1us();
- Delay1us();
- }
- uchar RcvByte(void)
- {
- uchar retc;
- uchar BitCnt;
- retc=0;
- SDA=1;
- for(BitCnt=0;BitCnt<8;BitCnt++)
- {
- Delay1us();
- SCL=0;
- Delay6us();
- SCL=1;
- Delay1us();
- Delay1us();
- retc=retc<<1;
- if(SDA==1)
- retc=retc+1;
- Delay1us();
- Delay1us();
- }
- SCL=0;
- Delay1us();
- Delay1us();
- return(retc);
- }
- void Ack_I2C(bit a)
- {
- if(a==0)
- SDA=0;
- else
- SDA=1;
- Delay1us();
- Delay1us();
- SCL=1;
- Delay6us();
- SCL=0;
- Delay1us();
- Delay1us();
- }
- uchar write_byte(uchar addr, uchar write_data)
- {
- Start_I2C();
- SendByte(DS3231_WriteAddress);
- if (ack == 0)
- return 0;
- SendByte(addr);
- if (ack == 0)
- return 0;
- SendByte(write_data);
- if (ack == 0)
- return 0;
- Stop_I2C();
- Delay6us();
- Delay6us();
- return 1;
- }
- uchar read_current()
- {
- uchar read_data;
- Start_I2C();
- SendByte(DS3231_ReadAddress);
- if(ack==0)
- return(0);
- read_data = RcvByte();
- Ack_I2C(1);
- Stop_I2C();
- return read_data;
- }
- uchar read_random(uchar random_addr)
- {
- uchar ret = 0;
- Start_I2C();
- SendByte(DS3231_WriteAddress);
- if(ack==0)
- {
- return ret;
- }
- SendByte(random_addr);
- if(ack==0)
- {
- return ret;
- }
- ret = read_current();
- return ret;
- }
- #define MBCD(n) (((n/10)<<4)|(n%10))
- void time_init(void)
- {
- write_byte(0x00,MBCD(00));
- write_byte(0x01,MBCD(36));
- write_byte(0x02,MBCD(18));
- write_byte(0x03,MBCD(3));
- write_byte(0x04,MBCD(18));
- write_byte(0x05,MBCD(10));
- write_byte(0x06,MBCD(17));
- write_byte(0x0E,0);
- }
- void DS3231_test(void)
- {
- uchar i = 0, tmp = 0;
- for(i = 0; i < 7; i++)
- {
- times[i] = read_random(i);
- // uart1_send(times[i]);
- tmp = (times[i]>>4)*10+(times[i]&0x0F);
- times[i] = tmp;
- }
- timenum = mktime(times[6]+2000,times[5],times[4],times[2],times[1],times[0]);
- timenum = timenum - 28800;
- }
复制代码 |