| 1 |
|
| 2 |
|
| 3 |
#include <commonlib/bsd/bcd.h> |
| 4 |
#include <device/i2c_simple.h> |
| 5 |
#include <rtc.h> |
| 6 |
#include <stdint.h> |
| 7 |
|
| 8 |
enum AS3722_RTC_REG |
| 9 |
{ |
| 10 |
AS3722_RTC_CONTROL = 0x60, |
| 11 |
AS3722_RTC_SECOND = 0x61, |
| 12 |
AS3722_RTC_MINUTE = 0x62, |
| 13 |
AS3722_RTC_HOUR = 0x63, |
| 14 |
AS3722_RTC_DAY = 0x64, |
| 15 |
AS3722_RTC_MONTH = 0x65, |
| 16 |
AS3722_RTC_YEAR = 0x66 |
| 17 |
}; |
| 18 |
|
| 19 |
enum { |
| 20 |
AS3722_RTC_CONTROL_ON = 0x1 << 2 |
| 21 |
}; |
| 22 |
|
| 23 |
static uint8_t as3722_read(enum AS3722_RTC_REG reg) |
| 24 |
{ |
| 25 |
uint8_t val; |
| 26 |
i2c_readb(CONFIG_DRIVERS_AS3722_RTC_BUS, |
| 27 |
CONFIG_DRIVERS_AS3722_RTC_ADDR, reg, &val); |
| 28 |
return val; |
| 29 |
} |
| 30 |
|
| 31 |
static void as3722_write(enum AS3722_RTC_REG reg, uint8_t val) |
| 32 |
{ |
| 33 |
i2c_writeb(CONFIG_DRIVERS_AS3722_RTC_BUS, |
| 34 |
CONFIG_DRIVERS_AS3722_RTC_ADDR, reg, val); |
| 35 |
} |
| 36 |
|
| 37 |
static void as3722rtc_init(void) |
| 38 |
{ |
| 39 |
static int initialized; |
| 40 |
if (initialized) |
| 41 |
return; |
| 42 |
|
| 43 |
uint8_t control = as3722_read(AS3722_RTC_CONTROL); |
| 44 |
as3722_write(AS3722_RTC_CONTROL, control | AS3722_RTC_CONTROL_ON); |
| 45 |
|
| 46 |
initialized = 1; |
| 47 |
} |
| 48 |
|
| 49 |
int rtc_set(const struct rtc_time *time) |
| 50 |
{ |
| 51 |
as3722rtc_init(); |
| 52 |
|
| 53 |
as3722_write(AS3722_RTC_SECOND, bin2bcd(time->sec)); |
| 54 |
as3722_write(AS3722_RTC_MINUTE, bin2bcd(time->min)); |
| 55 |
as3722_write(AS3722_RTC_HOUR, bin2bcd(time->hour)); |
| 56 |
as3722_write(AS3722_RTC_DAY, bin2bcd(time->mday)); |
| 57 |
as3722_write(AS3722_RTC_MONTH, bin2bcd(time->mon)); |
| 58 |
as3722_write(AS3722_RTC_YEAR, bin2bcd(time->year)); |
| 59 |
return 0; |
| 60 |
} |
| 61 |
|
| 62 |
int rtc_get(struct rtc_time *time) |
| 63 |
{ |
| 64 |
as3722rtc_init(); |
| 65 |
|
| 66 |
time->sec = bcd2bin(as3722_read(AS3722_RTC_SECOND) & 0x7f); |
| 67 |
time->min = bcd2bin(as3722_read(AS3722_RTC_MINUTE) & 0x7f); |
| 68 |
time->hour = bcd2bin(as3722_read(AS3722_RTC_HOUR) & 0x3f); |
| 69 |
time->mday = bcd2bin(as3722_read(AS3722_RTC_DAY) & 0x3f); |
| 70 |
time->mon = bcd2bin(as3722_read(AS3722_RTC_MONTH) & 0x1f); |
| 71 |
time->year = bcd2bin(as3722_read(AS3722_RTC_YEAR) & 0x7f); |
| 72 |
return 0; |
| 73 |
} |