34
34
#define HEX2DEC (val ) ((val >> 4U) * 10U + val % 16U) // Hex to Dec conversion macro
35
35
#define DEC2HEX (val ) ((val / 10U) * 16U + val % 10U) // Dec to Hex conversion macro
36
36
37
- static int flag = 0 ;
37
+ static int rtc_inited = 0 ;
38
38
static int diff_year = 100 ; //our RTC register only support 2000~2099
39
39
static void external_losc_enable (void );
40
40
41
41
void rtc_init (void )
42
42
{
43
- if (!flag ) {
43
+ if (!rtc_inited ) {
44
44
TSB_CG_FSYSENB_IPENB03 = 1 ; // Enable Sys Clock for RTC
45
45
external_losc_enable (); // Enable low-speed oscillator
46
- TSB_RTC -> PAGER = 0x00 ; //disable clock and alarm
46
+ TSB_RTC -> PAGER = 0x00 ; // Disable clock and alarm
47
47
48
48
while ((TSB_RTC -> RESTR & RTCRESTR_RSTTMR_MASK ) == RTCRESTR_RSTTMR_R_RUN ) {
49
49
// Reset RTC sec counter
@@ -66,24 +66,27 @@ void rtc_init(void)
66
66
TSB_RTC -> MINR = (uint8_t )0x02 ; // Set minute value
67
67
TSB_RTC -> SECR = (uint8_t )0x22 ; // Set second value
68
68
TSB_RTC -> PAGER |= RTC_CLK_ENABLE ; // Enable Clock
69
- flag = 1 ; // Enable internal flag
69
+ rtc_inited = 1 ; // Enable RTC initialzed status
70
70
}
71
71
}
72
72
73
73
void rtc_free (void )
74
74
{
75
- if (flag ) { // Check status of RTC peripheral driver is ENABLE or DISABLE
76
- flag = 0 ; // Set status of RTC peripheral driver is DISABLE
77
- }
75
+ rtc_inited = 0 ; // Set status of RTC peripheral driver as DISABLE
78
76
}
79
77
80
78
int rtc_isenabled (void )
81
79
{
82
- return flag ; // Return a flag that represents status of RTC peripheral driver
80
+ return rtc_inited ; // Return status of RTC peripheral driver
83
81
}
84
82
85
83
time_t rtc_read (void )
86
84
{
85
+ if (!rtc_inited ) {
86
+ // Return invalid time for now!
87
+ return 0 ;
88
+ }
89
+
87
90
struct tm timeinfo ;
88
91
uint8_t read_1 = 0U ;
89
92
uint8_t read_2 = 0U ;
@@ -141,6 +144,11 @@ time_t rtc_read(void)
141
144
142
145
void rtc_write (time_t t )
143
146
{
147
+ if (!rtc_inited ) {
148
+ // Initialize the RTC as not yet initialized
149
+ rtc_init ();
150
+ }
151
+
144
152
struct tm timeinfo ;
145
153
if (_rtc_localtime (t , & timeinfo , RTC_4_YEAR_LEAP_YEAR_SUPPORT ) == false) {
146
154
return ;
0 commit comments