Skip to content

Commit 19a5117

Browse files
committed
drivers/sf32lb52/lptim_systick: use averaged calibration value and add safety guards
Read RTC_BACKUP_LPCYCLE_AVE (freshly calibrated) instead of RTC_BACKUP_LPCYCLE (stale boot-time value) in calibration timer callback. Add divide-by-zero guards in get_elapsed_ticks() and get_rc10k_freq() for robustness when calibration hasn't completed yet. Signed-off-by: Joshua Jun <[email protected]>
1 parent 13b627c commit 19a5117

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/fw/drivers/sf32lb52/lptim_systick.c

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,12 @@ static void prv_cal_timer_cb(void* data) {
4141

4242
HAL_RC_CAL_update_reference_cycle_on_48M(LXT_LP_CYCLE);
4343

44-
ref_cycle = HAL_Get_backup(RTC_BACKUP_LPCYCLE);
44+
// Use the averaged calibration value, not the boot-time value
45+
ref_cycle = HAL_Get_backup(RTC_BACKUP_LPCYCLE_AVE);
46+
if (ref_cycle == 0) {
47+
// Fallback to prevent divide-by-zero
48+
ref_cycle = 1200000;
49+
}
4550
s_one_tick_hz = ((48000000ULL * LXT_LP_CYCLE) / ref_cycle) / RTC_TICKS_HZ;
4651

4752
__HAL_LPTIM_COMPARE_SET(&s_lptim1_handle, s_one_tick_hz);
@@ -136,6 +141,11 @@ void lptim_systick_tickless_idle(uint32_t ticks_from_now)
136141

137142
uint32_t lptim_systick_get_elapsed_ticks(void)
138143
{
144+
// Guard against divide-by-zero if calibration hasn't run yet
145+
if (s_one_tick_hz == 0) {
146+
return 0;
147+
}
148+
139149
// Check if we woke up due to overflow (normal timer expiry) or early (GPIO, etc.)
140150
// Per Sifli docs, wakeup takes ~250us, during which CNT reloads to 0 and keeps counting.
141151
// If overflow occurred, use the programmed period; otherwise use current CNT.
@@ -202,6 +212,10 @@ uint32_t lptim_systick_get_rc10k_freq(void)
202212
{
203213
// s_one_tick_hz = rc10k_freq / RTC_TICKS_HZ
204214
// Therefore: rc10k_freq = s_one_tick_hz * RTC_TICKS_HZ
215+
// Return a sensible default if not yet calibrated to avoid divide-by-zero in callers
216+
if (s_one_tick_hz == 0) {
217+
return 10000; // ~10kHz default
218+
}
205219
return s_one_tick_hz * RTC_TICKS_HZ;
206220
}
207221

0 commit comments

Comments
 (0)