3434#define HEX2DEC (val ) ((val >> 4U) * 10U + val % 16U) // Hex to Dec conversion macro
3535#define DEC2HEX (val ) ((val / 10U) * 16U + val % 10U) // Dec to Hex conversion macro
3636
37- static int flag = 0 ;
37+ static int rtc_inited = 0 ;
3838static int diff_year = 100 ; //our RTC register only support 2000~2099
3939static void external_losc_enable (void );
4040
4141void rtc_init (void )
4242{
43- if (!flag ) {
43+ if (!rtc_inited ) {
4444 TSB_CG_FSYSENA_IPENA23 = 1 ; // Enable Sys Clock for RTC
4545 external_losc_enable (); // Enable low-speed oscillator
4646
47- TSB_RTC -> PAGER = 0x00 ; //disable clock and alarm
47+ TSB_RTC -> PAGER = 0x00 ; // Disable clock and alarm
4848
4949 while ((TSB_RTC -> RESTR & RTCRESTR_RSTTMR_MASK ) == RTCRESTR_RSTTMR_R_RUN ) {
5050 // Reset RTC sec counter
@@ -68,24 +68,27 @@ void rtc_init(void)
6868 TSB_RTC -> MINR = (uint8_t )0x02 ; // Set minute value
6969 TSB_RTC -> SECR = (uint8_t )0x22 ; // Set second value
7070 TSB_RTC -> PAGER |= RTC_CLK_ENABLE ; // Enable Clock
71- flag = 1 ; // Enable internal flag
71+ rtc_inited = 1 ; // Enable RTC initialzed status
7272 }
7373}
7474
7575void rtc_free (void )
7676{
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
8078}
8179
8280int rtc_isenabled (void )
8381{
84- return flag ; // Return a flag that represents status of RTC peripheral driver
82+ return rtc_inited ; // Return status of RTC peripheral driver
8583}
8684
8785time_t rtc_read (void )
8886{
87+ if (!rtc_inited ) {
88+ // Return invalid time for now!
89+ return 0 ;
90+ }
91+
8992 struct tm timeinfo ;
9093 uint8_t read_1 = 0U ;
9194 uint8_t read_2 = 0U ;
@@ -143,6 +146,11 @@ time_t rtc_read(void)
143146
144147void rtc_write (time_t t )
145148{
149+ if (!rtc_inited ) {
150+ // Initialize the RTC as not yet initialized
151+ rtc_init ();
152+ }
153+
146154 struct tm timeinfo ;
147155 if (_rtc_localtime (t , & timeinfo , RTC_4_YEAR_LEAP_YEAR_SUPPORT ) == false) {
148156 return ;
0 commit comments