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_FSYSENA_IPENA23 = 1 ; // Enable Sys Clock for RTC
45
45
external_losc_enable (); // Enable low-speed oscillator
46
46
47
- TSB_RTC -> PAGER = 0x00 ; //disable clock and alarm
47
+ TSB_RTC -> PAGER = 0x00 ; // Disable clock and alarm
48
48
49
49
while ((TSB_RTC -> RESTR & RTCRESTR_RSTTMR_MASK ) == RTCRESTR_RSTTMR_R_RUN ) {
50
50
// Reset RTC sec counter
@@ -68,24 +68,27 @@ void rtc_init(void)
68
68
TSB_RTC -> MINR = (uint8_t )0x02 ; // Set minute value
69
69
TSB_RTC -> SECR = (uint8_t )0x22 ; // Set second value
70
70
TSB_RTC -> PAGER |= RTC_CLK_ENABLE ; // Enable Clock
71
- flag = 1 ; // Enable internal flag
71
+ rtc_inited = 1 ; // Enable RTC initialzed status
72
72
}
73
73
}
74
74
75
75
void rtc_free (void )
76
76
{
77
- if (flag ) { // Check status of RTC peripheral driver is ENABLE or DISABLE
78
- flag = 0 ; // Set status of RTC peripheral driver is DISABLE
79
- }
77
+ rtc_inited = 0 ; // Set status of RTC peripheral driver as DISABLE
80
78
}
81
79
82
80
int rtc_isenabled (void )
83
81
{
84
- return flag ; // Return a flag that represents status of RTC peripheral driver
82
+ return rtc_inited ; // Return status of RTC peripheral driver
85
83
}
86
84
87
85
time_t rtc_read (void )
88
86
{
87
+ if (!rtc_inited ) {
88
+ // Return invalid time for now!
89
+ return 0 ;
90
+ }
91
+
89
92
struct tm timeinfo ;
90
93
uint8_t read_1 = 0U ;
91
94
uint8_t read_2 = 0U ;
@@ -143,6 +146,11 @@ time_t rtc_read(void)
143
146
144
147
void rtc_write (time_t t )
145
148
{
149
+ if (!rtc_inited ) {
150
+ // Initialize the RTC as not yet initialized
151
+ rtc_init ();
152
+ }
153
+
146
154
struct tm timeinfo ;
147
155
if (_rtc_localtime (t , & timeinfo , RTC_4_YEAR_LEAP_YEAR_SUPPORT ) == false) {
148
156
return ;
0 commit comments