]>
cloudbase.mooo.com Git - z180-stamp.git/blob - avr/pcf8583.c
2 * (C) Copyright 2014 Leo C. <erbl259-lmu@yahoo.de>
4 * SPDX-License-Identifier: GPL-2.0+
8 * Date & Time support for Philips PCF8583 RTC
21 #define debug_rtc(fmt, args...) \
22 debug_cond(DEBUG_RTC, fmt, ##args)
24 #define REG_CS 0x00 /* control/status */
25 #define REG_CSEC 0x01 /* hundredth of a second */
26 #define REG_SEC 0x02 /* seconds */
27 #define REG_MIN 0x03 /* minutes */
28 #define REG_HOUR 0x04 /* hours */
29 #define REG_YRDATE 0x05 /* year/date */
30 #define REG_WDMON 0x06 /* weekdays/months */
34 /* ------------------------------------------------------------------------- */
36 static uint_fast8_t bcd2bin(uint8_t val
)
38 return (val
>> 4) * 10 + (val
& 0x0f);
41 static uint8_t bin2bcd (uint_fast8_t val
)
43 div_t d
= div(val
, 10);
45 return (d
.quot
<< 4) | d
.rem
;
49 int rtc_get (struct tm
*tmp
)
52 uint8_t rtcbuf
[NR_OF_REGS
];
55 i2c_read(CONFIG_SYS_I2C_RTC_ADDR
, 0, 1, rtcbuf
, NR_OF_REGS
);
56 i2c_read(CONFIG_SYS_I2C_RTC_ADDR
, 0x10, 1, (uint8_t *) &year
, 2);
58 debug_rtc("Get RTC year: %u, year/date: %02x, wdays/month: %02x, "
59 "hour: %02x, min: %02x, sec: %02x, (stat: %02x)\n", year
,
60 rtcbuf
[6], rtcbuf
[5], rtcbuf
[4], rtcbuf
[3], rtcbuf
[2], rtcbuf
[0]);
62 tmp
->tm_sec
= bcd2bin (rtcbuf
[REG_SEC
] & 0x7F);
63 tmp
->tm_min
= bcd2bin (rtcbuf
[REG_MIN
] & 0x7F);
64 tmp
->tm_hour
= bcd2bin (rtcbuf
[REG_HOUR
] & 0x3F);
65 tmp
->tm_mday
= bcd2bin (rtcbuf
[REG_YRDATE
] & 0x3F);
66 tmp
->tm_mon
= bcd2bin (rtcbuf
[REG_WDMON
] & 0x1F) - 1;
67 while (year
%4 < (rtcbuf
[REG_YRDATE
]>>6)) {
69 /* TODO: update RTC ram */
72 tmp
->tm_wday
= rtcbuf
[REG_WDMON
] >> 5;
77 debug_rtc( "Get DATE: %4d-%02d-%02d (wday=%d) TIME: %2d:%02d:%02d\n",
78 tmp
->tm_year
, tmp
->tm_mon
, tmp
->tm_mday
, tmp
->tm_wday
,
79 tmp
->tm_hour
, tmp
->tm_min
, tmp
->tm_sec
);
84 int rtc_set (struct tm
*tmp
)
86 uint8_t rtcbuf
[NR_OF_REGS
];
88 debug_rtc("Set DATE: %4d-%02d-%02d (wday=%d) TIME: %2d:%02d:%02d\n",
89 tmp
->tm_year
, tmp
->tm_mon
, tmp
->tm_mday
, tmp
->tm_wday
,
90 tmp
->tm_hour
, tmp
->tm_min
, tmp
->tm_sec
);
92 rtcbuf
[REG_CS
] = 0x84;
93 rtcbuf
[REG_CSEC
] = 0x00;
94 rtcbuf
[REG_WDMON
] = (bin2bcd(tmp
->tm_mon
) + 1) | ((tmp
->tm_wday
) << 5);
95 rtcbuf
[REG_YRDATE
] = ((tmp
->tm_year
% 4) << 6) | bin2bcd(tmp
->tm_mday
);
96 rtcbuf
[REG_HOUR
] = bin2bcd(tmp
->tm_hour
);
97 rtcbuf
[REG_MIN
] = bin2bcd(tmp
->tm_min
);
98 rtcbuf
[REG_SEC
] = bin2bcd(tmp
->tm_sec
);
100 i2c_write(CONFIG_SYS_I2C_RTC_ADDR
, 0, 1, rtcbuf
, NR_OF_REGS
);
101 i2c_write(CONFIG_SYS_I2C_RTC_ADDR
, 0x10, 1, (uint8_t *) &tmp
->tm_year
, 2);
102 rtcbuf
[REG_CS
] = 0x04;
103 i2c_write(CONFIG_SYS_I2C_RTC_ADDR
, 0, 1, rtcbuf
, 1);