88
99#include "bf0_hal_rtc.h"
1010
11+ #include "rtconfig.h"
12+
1113// The RTC clock, CLK_RTC, can be configured to use the LXT32 (32.768 kHz) or
1214// LRC10 (9.8 kHz). The prescaler values need to be set such that the CLK1S
1315// event runs at 1 Hz. The formula that relates prescaler values with the
@@ -29,14 +31,86 @@ static RTC_HandleTypeDef RTC_Handler = {
2931 },
3032};
3133
34+ uint32_t rtc_get_lpcycle ()
35+ {
36+ uint32_t value ;
37+ #ifdef BF0_HCPU
38+ value = HAL_Get_backup (RTC_BACKUP_LPCYCLE_AVE );
39+ if (value == 0 )
40+ value = 1200000 ;
41+ value += BSP_RTC_PPM ; // Calibrate in initial with 8 cycle
42+ HAL_Set_backup (RTC_BACKUP_LPCYCLE , (uint32_t )value );
43+ #else
44+ value = HAL_Get_backup (RTC_BACKUP_LPCYCLE );
45+ #endif
46+ return value ;
47+ }
48+
49+ static uint32_t soft_rc10_backup = 0 ;
50+ static uint16_t rc10_freq_khz ;
51+
52+ void drv_set_soft_rc10_backup (uint32_t backup )
53+ {
54+ soft_rc10_backup = backup ;
55+ /* RC10K freq_khz = 48000 * LXT_LP_CYCLE / v; */
56+ rc10_freq_khz = (uint16_t )(48000UL * LXT_LP_CYCLE / backup );
57+ }
58+
59+ void rtc_rc10_calculate_div (RTC_HandleTypeDef * hdl , uint32_t value )
60+ {
61+ hdl -> Init .DivB = RC10K_SUB_SEC_DIVB ;
62+
63+ // 1 seconds has total 1/(x/(48*8))/256=1.5M/x cycles, times 2^14 for DIVA
64+ uint32_t divider = RTC_Handler .Init .DivB * value ;
65+ value = ((uint64_t )48000000 * LXT_LP_CYCLE * (1 << 14 ) + (divider >> 1 )) / divider ;
66+ hdl -> Init .DivAInt = (uint32_t )(value >> 14 );
67+ hdl -> Init .DivAFrac = (uint32_t )(value & ((1 << 14 ) - 1 ));
68+ }
69+
3270void rtc_init (void ) {
33- HAL_StatusTypeDef ret ;
71+ // periph_config_acquire_lock();
72+ // rtc_enable_backup_regs();
73+
74+ #ifndef LXT_DISABLE
75+ #ifdef SF32LB52X
76+ HAL_PMU_EnableXTAL32 ();
77+ if (HAL_PMU_LXTReady () != HAL_OK )
78+ #else
79+ if (HAL_RTC_LXT_ENABLED () && HAL_PMU_LXTReady () != HAL_OK )
80+ #endif
81+ {
82+ PBL_LOG (LOG_LEVEL_ALWAYS , "RTC init fail" );
83+ WTF ;
84+ }
85+ HAL_RTC_ENABLE_LXT ();
86+ #endif
87+
88+ uint32_t wakesrc = RTC_INIT_NORMAL ;
89+
90+ #ifdef LXT_DISABLE
91+ {
92+ uint64_t value = 0 ;
93+ value = rtc_get_lpcycle ();
94+ drv_set_soft_rc10_backup ((uint32_t )value );
95+ if (value )
96+ rtc_rc10_calculate_div (& RTC_Handler , value );
97+ }
98+ #endif
99+
100+ if (HAL_RTC_Init (& RTC_Handler , wakesrc ) != HAL_OK )
101+ {
102+ WTF ;
103+ }
104+
105+ // periph_config_release_lock();
34106
35- ret = HAL_PMU_LXTReady ();
36- PBL_ASSERTN ( ret == HAL_OK );
107+ // restore_rtc_time_state ();
108+ // initialize_fast_mode_state( );
37109
38- ret = HAL_RTC_Init (& RTC_Handler , RTC_INIT_NORMAL );
39- PBL_ASSERTN (ret == HAL_OK );
110+ // #ifdef PBL_LOG_ENABLED
111+ // char buffer[TIME_STRING_BUFFER_SIZE];
112+ // PBL_LOG(LOG_LEVEL_DEBUG, "Current time is <%s>", rtc_get_time_string(buffer));
113+ // #endif
40114}
41115
42116void rtc_init_timers (void ) {}
0 commit comments