Skip to content

Commit 46d5403

Browse files
added support for the Portenta C33
optimized micros()
1 parent 8dcbd08 commit 46d5403

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

cores/arduino/time.cpp

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,21 +19,23 @@ __attribute__((weak)) void yield() {
1919
}
2020

2121
static FspTimer main_timer;
22-
// specifying these details as constants makes micros() faster !
23-
#define _timer_type AGT_TIMER
24-
#define _timer_index 0
25-
#define _timer_get_underflow_bit() R_AGT0->AGTCR_b.TUNDF
26-
#define _timer_clock_divider TIMER_SOURCE_DIV_8 // dividers 1, 2 and 8 work because _timer_period is < 16-bit. the divider 4 seems not supported: acts as 1
27-
#define _timer_clock_freq 24000000UL
28-
#define _timer_counts_per_us (_timer_clock_freq / ((1 << _timer_clock_divider) * 1000000UL))
29-
#define _timer_period (_timer_counts_per_us * 1000UL)
30-
#define TIMER_PRIORITY 8
22+
const uint8_t _timer_type = AGT_TIMER;
23+
const uint8_t _timer_index = 0;
24+
inline uint8_t _timer_get_underflow_bit() { return R_AGT0->AGTCR_b.TUNDF; }
25+
// clock divider 8 works for the Uno R4 and Portenta C33 both because _timer_period is < 16-bit.
26+
// on the Uno R4 the AGT clock is 24 MHz / 8 -> 3000 ticks per ms
27+
// on the Portenta C33 the AGT clock is 50 Mhz / 8 -> 6250 ticks per ms
28+
const timer_source_div_t _timer_clock_divider = TIMER_SOURCE_DIV_8;
29+
uint32_t _timer_period;
30+
const uint8_t TIMER_PRIORITY = 8;
3131

3232
static void timer_micros_callback(timer_callback_args_t __attribute((unused))* p_args) {
3333
agt_time_ms += 1;
3434
}
3535

3636
void startAgt() {
37+
const uint32_t _timer_clock_freq = R_FSP_SystemClockHzGet(_timer_type == AGT_TIMER ? FSP_PRIV_CLOCK_PCLKB : FSP_PRIV_CLOCK_PCLKD);
38+
_timer_period = _timer_clock_freq / ((1 << _timer_clock_divider) * 1000UL);
3739
main_timer.begin(TIMER_MODE_PERIODIC, _timer_type, _timer_index, _timer_period, 1, _timer_clock_divider, timer_micros_callback);;
3840
main_timer.setup_overflow_irq(TIMER_PRIORITY);
3941
main_timer.open();
@@ -61,5 +63,5 @@ unsigned long micros() {
6163
}
6264
NVIC_EnableIRQ(main_timer.get_cfg()->cycle_end_irq);
6365
uint32_t const up_counts = (_timer_period - 1) - down_counts;
64-
return (ms * 1000) + (up_counts / _timer_counts_per_us);
66+
return (ms * 1000) + ((up_counts * 1000) / _timer_period);
6567
}

0 commit comments

Comments
 (0)