/*********************************************************
*Copyright (C), 2023, Shanghai Eastsoft Microelectronics Co., Ltd
*文件名:  rtc.h
*作  者:  AE Team
*版  本:  v1.0，编译于iDesigner(v4.2.3.187) + 工具链HRCC(v1.2.0.136)
*日  期:  2023/01/31
*描  述:  RTC驱动头文件
注意:DS1302写寄存器是地址是偶数,读的时候地址+1
比如:往0x80地址写入0x01,读取时需要从0x81读取
*****************************************************************************/
#ifndef RTC_H
#define RTC_H

#include <HIC.h>
#include "types.h"

/**
 * PB0 - IO 
 * PA6 - SCLK 
 * PB1 - RST 
 */

#define BIT(n)                          (1 << n)

#define KY1302_CLK_PT
 
#define DS1302_IO_INIT()	do {		\
	PBT0 = 0;							\
	PBPU0 = 1;							\
	PAT6 = 0;							\
	PAPU6 = 1;							\
	PBT1 = 0;							\
	PBPU1 = 1;							\
} while(0)

#define DS1302_IO_HIGH()       	do { PB0 = 1; } while(0)
#define DS1302_IO_LOW()         do { PB0 = 0; } while(0)
#define DS1302_IO_IN()          do { PBT0 = 1; } while(0)
#define DS1302_IO_OUT()         do { PBT0 = 0; } while(0)
#define DS1302_IO_IS_HIGH()     (PB0)

#define DS1302_CLK_HIGH()		do { PA6 = 1; } while(0)
#define DS1302_CLK_LOW()    	do { PA6 = 0; } while(0)

#define DS1302_RST_HIGH()       do { PB1 = 1; } while(0)
#define DS1302_RST_LOW()        do { PB1 = 0; } while(0)
 
#define SEC_ADR                         0x80
#define MIN_ADR                         0x82
#define HOU_ADR                         0x84
#define DAY_ADR                         0x86
#define MON_ADR                         0x88
#define YEA_ADR                         0x8C
 
#define WRITE_SW_ADR                    0x8E //写保护地址
 
#define CHARGE_ADR                      0x90 //充电写地址<读为0x91>
#define TCS_ON                          0xA0
#define TCS_OFF                         0x00
#define DS_DIODE_ONE                    0x04 //VCC2和VCC1之间1个二极管充电
#define DS_DIODE_TWO                    0x08 //VCC2和VCC1之间2个二极管充电
#define DS_OFF                          0x00 //充电被禁止
#define CS_RES_NO                       0x01 //无电阻
#define CS_RES_2K                       0x01 //2K电阻
#define CS_RES_4K                       0x02 //4K电阻
#define CS_RES_8K                       0x03 //8K电阻
 
#define HOURLY_24                       0x00
#define HOURLY_12                       0x01
 
#define HOURLY_PM                       0x00
#define HOURLY_AM                       0x01

typedef struct {
    uint8_t year;     //取值00~99
    uint8_t month;
    uint8_t day;
    uint8_t hour;
    uint8_t minute;
    uint8_t second;
    uint8_t wday;
} type_time;
 
uint8_t bcd_dec(uint8_t bcd);
uint8_t dec_bcd(uint8_t dec);
void ds1302_write(uint8_t adr,uint8_t dat);
uint8_t ds1302_read(uint8_t adr);
void ds1302_init(void);
void ds1302_write_time(void);
void ds1302_read_time(void);
uint8_t week_conversion(uint8_t year, uint8_t month, uint8_t day);

void ds1302_write_ram(uint8_t *buf, uint8_t len);
void ds1302_read_ram(uint8_t *buf, uint8_t len);

extern type_time t_time;
 
#endif
