Skip to content

Commit 1663233

Browse files
Raffael Rostagnohenrikbrixandersen
authored andcommitted
drivers: counter: rtc: esp32: Fix overflow case
Fix alarm setting when timer has overflown beyond 32-bit boundary. Timer is 48-bit, so it requires high word to be programmed along the 32-bit word managed by the driver. Signed-off-by: Raffael Rostagno <[email protected]>
1 parent a71f2ba commit 1663233

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

drivers/counter/counter_esp32_rtc.c

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -91,13 +91,22 @@ static int counter_esp32_get_value(const struct device *dev, uint32_t *ticks)
9191
return 0;
9292
}
9393

94+
static int counter_esp32_get_value_64(const struct device *dev, uint64_t *ticks)
95+
{
96+
ARG_UNUSED(dev);
97+
98+
*ticks = rtc_cntl_ll_get_rtc_time();
99+
100+
return 0;
101+
}
102+
94103
static int counter_esp32_set_alarm(const struct device *dev, uint8_t chan_id,
95104
const struct counter_alarm_cfg *alarm_cfg)
96105
{
97106
ARG_UNUSED(chan_id);
98107
struct counter_esp32_data *data = dev->data;
99-
uint32_t now;
100-
uint32_t ticks = 0;
108+
uint64_t now;
109+
uint64_t ticks = 0;
101110

102111
#if defined(CONFIG_SOC_SERIES_ESP32) || defined(CONFIG_SOC_SERIES_ESP32C2) || \
103112
defined(CONFIG_SOC_SERIES_ESP32C3)
@@ -109,15 +118,21 @@ static int counter_esp32_set_alarm(const struct device *dev, uint8_t chan_id,
109118
data->alarm_cfg.callback = alarm_cfg->callback;
110119
data->alarm_cfg.user_data = alarm_cfg->user_data;
111120

112-
counter_esp32_get_value(dev, &now);
121+
counter_esp32_get_value_64(dev, &now);
113122

114-
ticks = (alarm_cfg->flags & COUNTER_ALARM_CFG_ABSOLUTE) ? alarm_cfg->ticks
115-
: now + alarm_cfg->ticks;
123+
if (alarm_cfg->flags & COUNTER_ALARM_CFG_ABSOLUTE) {
124+
ticks = (now & ~0xFFFFFFFFULL) | alarm_cfg->ticks;
125+
if (ticks < now) {
126+
ticks += (1ULL << 32);
127+
}
128+
} else {
129+
ticks = now + alarm_cfg->ticks;
130+
}
116131

117132
rtc_cntl_ll_set_wakeup_timer(ticks);
118133

119134
/* RTC main timer set alarm value */
120-
CLEAR_PERI_REG_MASK(RTC_CNTL_SLP_TIMER1_REG, 0xffffffff);
135+
CLEAR_PERI_REG_MASK(RTC_CNTL_SLP_TIMER1_REG, 0xFFFFFFFF);
121136

122137
/* RTC main timer set alarm enable */
123138
SET_PERI_REG_MASK(RTC_CNTL_SLP_TIMER1_REG, RTC_CNTL_MAIN_TIMER_ALARM_EN);
@@ -200,6 +215,7 @@ static DEVICE_API(counter, rtc_timer_esp32_api) = {
200215
.start = counter_esp32_start,
201216
.stop = counter_esp32_stop,
202217
.get_value = counter_esp32_get_value,
218+
.get_value_64 = counter_esp32_get_value_64,
203219
.set_alarm = counter_esp32_set_alarm,
204220
.cancel_alarm = counter_esp32_cancel_alarm,
205221
.set_top_value = counter_esp32_set_top_value,

0 commit comments

Comments
 (0)