diff --git a/cores/arduino/stm32/HardwareTimer.cpp b/cores/arduino/stm32/HardwareTimer.cpp index 504bc350fb..bf97cae7fa 100644 --- a/cores/arduino/stm32/HardwareTimer.cpp +++ b/cores/arduino/stm32/HardwareTimer.cpp @@ -31,10 +31,47 @@ /* Private Defines */ #define PIN_NOT_USED 0xFF -#define MAX_RELOAD ((1 << 16) - 1) // Currently even 32b timers are used as 16b to have generic behavior #define REGULAR_CHAN_MASK 0x01 #define COMPLEMENTARY_CHAN_MASK 0x10 +// Keep the initial period for sketches that start a timer without setting it. +static constexpr uint32_t DEFAULT_RELOAD = UINT16_MAX; +static constexpr uint32_t MAX_PRESCALE_FACTOR = UINT16_MAX + 1U; +static constexpr uint32_t MICROS_PER_SECOND = 1000000U; + +static uint32_t maxTimerCount(TIM_TypeDef *instance) +{ +#if defined(IS_TIM_32B_COUNTER_INSTANCE) + return IS_TIM_32B_COUNTER_INSTANCE(instance) ? UINT32_MAX : UINT16_MAX; +#else + (void)instance; + return UINT16_MAX; +#endif +} + +static uint32_t limitTimerValue(uint64_t value, uint32_t limit) +{ + return value > limit ? limit : static_cast(value); +} + +static uint64_t timerPeriodTicks(TIM_TypeDef *instance) +{ + return uint64_t(LL_TIM_GetAutoReload(instance)) + 1; +} + +static uint64_t timerCyclesToMicros(uint64_t cycles, uint32_t clock) +{ + if (clock == 0) { + return 0; + } + // The full timer period with prescaling can exceed UINT64_MAX when scaled + // by a million. Divide before converting the whole seconds. + const uint64_t seconds = cycles / clock; + const uint64_t micros = ((cycles % clock) * MICROS_PER_SECOND) / clock; + return seconds > (UINT64_MAX - micros) / MICROS_PER_SECOND ? + UINT64_MAX : seconds * MICROS_PER_SECOND + micros; +} + /* Private Variables */ timerObj_t *HardwareTimer_Handle[TIMER_NUM] = {NULL}; @@ -135,7 +172,7 @@ void HardwareTimer::setup(TIM_TypeDef *instance) /* Configure timer with some default values */ config.prescaler = 0; config.counter_mode = HAL_TIM_COUNTER_UP; - config.period = MAX_RELOAD; + config.period = DEFAULT_RELOAD; config.repetition_counter = 0; config.clock_sel.clock_source = HAL_TIM_CLK_INTERNAL; HAL_TIM_SetConfig(&_timerObj.handle, &config); @@ -170,7 +207,7 @@ void HardwareTimer::setup(TIM_TypeDef *instance) _timerObj.handle.State = HAL_TIM_STATE_RESET; /* Configure timer with some default values */ _timerObj.handle.Init.Prescaler = 0; - _timerObj.handle.Init.Period = MAX_RELOAD; + _timerObj.handle.Init.Period = DEFAULT_RELOAD; _timerObj.handle.Init.CounterMode = TIM_COUNTERMODE_UP; _timerObj.handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; #if defined(TIM_RCR_REP) @@ -602,111 +639,106 @@ uint32_t HardwareTimer::getPrescaleFactor() void HardwareTimer::setPrescaleFactor(uint32_t prescaler) { - // Hardware register correspond to prescaler-1. Example PSC register value 0 means divided by 1 - LL_TIM_SetPrescaler(_timerObj.instance, prescaler - 1); + // PSC stores the prescale factor minus one. + prescaler = limitTimerValue(prescaler, MAX_PRESCALE_FACTOR); + LL_TIM_SetPrescaler(_timerObj.instance, prescaler > 0 ? prescaler - 1 : 0); updateRegistersIfNotRunning(_timerObj.instance); } -uint32_t HardwareTimer::getOverflow(TimerFormat_t format) +uint64_t HardwareTimer::getOverflow(TimerFormat_t format) { - // Hardware register correspond to period count-1. Example ARR register value 9 means period of 10 timer cycle - uint32_t ARR_RegisterValue = LL_TIM_GetAutoReload(_timerObj.instance); - uint32_t Prescalerfactor = LL_TIM_GetPrescaler(_timerObj.instance) + 1; - uint32_t return_value; + const uint64_t ticks = timerPeriodTicks(_timerObj.instance); + const uint64_t cycles = ticks * getPrescaleFactor(); switch (format) { case MICROSEC_FORMAT: - return_value = (uint32_t)(((ARR_RegisterValue + 1) * Prescalerfactor * 1000000.0) / getTimerClkFreq()); - break; + return timerCyclesToMicros(cycles, getTimerClkFreq()); case HERTZ_FORMAT: - return_value = (uint32_t)(getTimerClkFreq() / ((ARR_RegisterValue + 1) * Prescalerfactor)); - break; + return getTimerClkFreq() / cycles; case TICK_FORMAT: - default : - return_value = ARR_RegisterValue + 1; - break; + default: + return ticks; } - return return_value; } -void HardwareTimer::setOverflow(uint32_t overflow, TimerFormat_t format) +void HardwareTimer::setOverflow(uint64_t overflow, TimerFormat_t format) { - uint32_t ARR_RegisterValue; - uint32_t PeriodTicks; - uint32_t Prescalerfactor; - uint32_t period_cyc; - // Remark: Hardware register correspond to period count-1. Example ARR register value 9 means period of 10 timer cycle - switch (format) { - case MICROSEC_FORMAT: - period_cyc = overflow * (getTimerClkFreq() / 1000000); - Prescalerfactor = (period_cyc / 0x10000) + 1; - LL_TIM_SetPrescaler(_timerObj.instance, Prescalerfactor - 1); - PeriodTicks = period_cyc / Prescalerfactor; - break; - case HERTZ_FORMAT: - period_cyc = getTimerClkFreq() / overflow; - Prescalerfactor = (period_cyc / 0x10000) + 1; - LL_TIM_SetPrescaler(_timerObj.instance, Prescalerfactor - 1); - PeriodTicks = period_cyc / Prescalerfactor; - break; - case TICK_FORMAT: - default : - PeriodTicks = overflow; - break; - } + const uint32_t maxCount = maxTimerCount(_timerObj.instance); + const uint64_t maxTicks = uint64_t(maxCount) + 1; + uint64_t ticks = overflow; + if (format == MICROSEC_FORMAT || format == HERTZ_FORMAT) { + const uint32_t clock = getTimerClkFreq(); + if (clock == 0 || (format == HERTZ_FORMAT && overflow == 0)) { + return; + } + const uint64_t maxCycles = maxTicks * MAX_PRESCALE_FACTOR; + uint64_t cycles; + if (format == MICROSEC_FORMAT && maxCount == UINT16_MAX) { + // Preserve the established 16-bit microsecond conversion. + const uint32_t cyclesPerMicro = clock / MICROS_PER_SECOND; + cycles = cyclesPerMicro != 0 && overflow > maxCycles / cyclesPerMicro ? + maxCycles : overflow * cyclesPerMicro; + } else if (format == MICROSEC_FORMAT) { + // Bound the whole seconds before multiplying. The remaining fraction + // takes fewer than one million microseconds and fits the calculation. + const uint64_t seconds = overflow / MICROS_PER_SECOND; + cycles = seconds > maxCycles / clock ? maxCycles : + seconds * clock + (overflow % MICROS_PER_SECOND) * clock / MICROS_PER_SECOND; + if (cycles > maxCycles) { + cycles = maxCycles; + } + } else { + cycles = clock / overflow; + } - if (PeriodTicks > 0) { - // The register specifies the maximum value, so the period is really one tick longer - ARR_RegisterValue = PeriodTicks - 1; - } else { - // But do not underflow in case a zero period was given somehow. - ARR_RegisterValue = 0; + // Keep the 16-bit prescaler bands, including headroom for CCR = ARR + 1 + // at exact multiples. For 32-bit timers, round up only when necessary. + const uint64_t prescaleInput = maxCount == UINT16_MAX || cycles == 0 ? cycles : cycles - 1; + const uint32_t factor = limitTimerValue(prescaleInput / maxTicks + 1, MAX_PRESCALE_FACTOR); + LL_TIM_SetPrescaler(_timerObj.instance, factor - 1); + ticks = cycles / factor; } - LL_TIM_SetAutoReload(_timerObj.instance, ARR_RegisterValue); + // ARR stores one less than the period. Zero still selects a one-tick period. + const uint32_t reload = ticks > 0 ? limitTimerValue(ticks - 1, maxCount) : 0; + LL_TIM_SetAutoReload(_timerObj.instance, reload); updateRegistersIfNotRunning(_timerObj.instance); } uint32_t HardwareTimer::getCount(TimerFormat_t format) { - uint32_t CNT_RegisterValue = LL_TIM_GetCounter(_timerObj.instance); - uint32_t Prescalerfactor = LL_TIM_GetPrescaler(_timerObj.instance) + 1; - uint32_t return_value; + const uint32_t count = LL_TIM_GetCounter(_timerObj.instance); + const uint64_t cycles = uint64_t(count) * getPrescaleFactor(); switch (format) { case MICROSEC_FORMAT: - return_value = (uint32_t)((CNT_RegisterValue * Prescalerfactor * 1000000.0) / getTimerClkFreq()); - break; + return limitTimerValue(timerCyclesToMicros(cycles, getTimerClkFreq()), UINT32_MAX); case HERTZ_FORMAT: - // CNT_RegisterValue is 0 right at/after every timer reset or overflow, - // which is a normal, reachable state (not a caller error): avoid a - // divide by zero and report 0 (no meaningful frequency available). - return_value = (CNT_RegisterValue == 0) ? 0 : (uint32_t)(getTimerClkFreq() / (CNT_RegisterValue * Prescalerfactor)); - break; + return count == 0 ? 0 : getTimerClkFreq() / cycles; case TICK_FORMAT: - default : - return_value = CNT_RegisterValue; - break; + default: + return count; } - return return_value; } void HardwareTimer::setCount(uint32_t counter, TimerFormat_t format) { - uint32_t CNT_RegisterValue; - uint32_t Prescalerfactor = LL_TIM_GetPrescaler(_timerObj.instance) + 1; + const uint32_t factor = getPrescaleFactor(); + uint64_t ticks = counter; switch (format) { case MICROSEC_FORMAT: - CNT_RegisterValue = ((counter * (getTimerClkFreq() / 1000000)) / Prescalerfactor); + ticks = uint64_t(counter) * getTimerClkFreq() / MICROS_PER_SECOND / factor; break; case HERTZ_FORMAT: - CNT_RegisterValue = (uint32_t)(getTimerClkFreq() / (counter * Prescalerfactor)); + if (counter == 0) { + return; + } + ticks = getTimerClkFreq() / (uint64_t(counter) * factor); break; case TICK_FORMAT: - default : - CNT_RegisterValue = counter; + default: break; } - LL_TIM_SetCounter(_timerObj.instance, CNT_RegisterValue); + LL_TIM_SetCounter(_timerObj.instance, limitTimerValue(ticks, maxTimerCount(_timerObj.instance))); } void HardwareTimer::setMode(uint32_t channel, TimerModes_t mode, pin_size_t pin, ChannelInputFilter_t filter) @@ -983,19 +1015,22 @@ void HardwareTimer::setPreloadEnable(bool value) void HardwareTimer::setCaptureCompare(uint32_t channel, uint32_t compare, TimerCompareFormat_t format) { - uint32_t Prescalerfactor = LL_TIM_GetPrescaler(_timerObj.instance) + 1; - uint32_t CCR_RegisterValue; + const uint32_t factor = getPrescaleFactor(); + uint64_t ticks; switch (format) { case MICROSEC_COMPARE_FORMAT: - CCR_RegisterValue = ((compare * (getTimerClkFreq() / 1000000)) / Prescalerfactor); + ticks = uint64_t(compare) * getTimerClkFreq() / MICROS_PER_SECOND / factor; break; case HERTZ_COMPARE_FORMAT: - CCR_RegisterValue = getTimerClkFreq() / (compare * Prescalerfactor); + if (compare == 0) { + return; + } + ticks = getTimerClkFreq() / (uint64_t(compare) * factor); break; // As per Reference Manual PWM reach 100% with CCRx value strictly greater than ARR (So ARR+1 in our case) case PERCENT_COMPARE_FORMAT: - CCR_RegisterValue = ((LL_TIM_GetAutoReload(_timerObj.instance) + 1) * compare) / 100; + ticks = timerPeriodTicks(_timerObj.instance) * compare / 100; break; case RESOLUTION_1B_COMPARE_FORMAT: case RESOLUTION_2B_COMPARE_FORMAT: @@ -1013,20 +1048,17 @@ void HardwareTimer::setCaptureCompare(uint32_t channel, uint32_t compare, TimerC case RESOLUTION_14B_COMPARE_FORMAT: case RESOLUTION_15B_COMPARE_FORMAT: case RESOLUTION_16B_COMPARE_FORMAT: - CCR_RegisterValue = ((LL_TIM_GetAutoReload(_timerObj.instance) + 1) * compare) / ((1 << format) - 1) ; + ticks = timerPeriodTicks(_timerObj.instance) * compare / ((1U << format) - 1); break; case TICK_COMPARE_FORMAT: default : - CCR_RegisterValue = compare; + ticks = compare; break; } - // Special case when ARR is set to the max value, it is not possible to set CCRx to ARR+1 to reach 100% - // Then set CCRx to max value. PWM is then 1/0xFFFF = 99.998..% - if ((LL_TIM_GetAutoReload(_timerObj.instance) == MAX_RELOAD) - && (CCR_RegisterValue == MAX_RELOAD + 1)) { - CCR_RegisterValue = MAX_RELOAD; - } + // At maximum ARR, ARR + 1 cannot be represented in CCR. Use the closest + // duty cycle the register can express, one tick short of a full period. + const uint32_t CCR_RegisterValue = limitTimerValue(ticks, maxTimerCount(_timerObj.instance)); switch (channel) { case 1: @@ -1051,8 +1083,7 @@ void HardwareTimer::setCaptureCompare(uint32_t channel, uint32_t compare, TimerC uint32_t HardwareTimer::getCaptureCompare(uint32_t channel, TimerCompareFormat_t format) { uint32_t CCR_RegisterValue = 0; - uint32_t Prescalerfactor = LL_TIM_GetPrescaler(_timerObj.instance) + 1; - uint32_t return_value; + uint64_t return_value; switch (channel) { case 1: @@ -1073,7 +1104,8 @@ uint32_t HardwareTimer::getCaptureCompare(uint32_t channel, TimerCompareFormat_ switch (format) { case MICROSEC_COMPARE_FORMAT: - return_value = (uint32_t)((CCR_RegisterValue * Prescalerfactor * 1000000.0) / getTimerClkFreq()); + return_value = timerCyclesToMicros(uint64_t(CCR_RegisterValue) * getPrescaleFactor(), + getTimerClkFreq()); break; case HERTZ_COMPARE_FORMAT: // CCR_RegisterValue is 0 on reset (before the first setCaptureCompare() @@ -1081,13 +1113,14 @@ uint32_t HardwareTimer::getCaptureCompare(uint32_t channel, TimerCompareFormat_ // landed exactly at CNT == 0 or before any edge has been captured yet. // That is a normal, reachable state (not a caller error): avoid a // divide by zero and report 0 (no meaningful frequency available). - return_value = (CCR_RegisterValue == 0) ? 0 : (uint32_t)(getTimerClkFreq() / (CCR_RegisterValue * Prescalerfactor)); + return_value = CCR_RegisterValue == 0 ? 0 : + getTimerClkFreq() / (uint64_t(CCR_RegisterValue) * getPrescaleFactor()); break; // As per Reference Manual PWM reach 100% with CCRx value strictly greater than ARR // (So ARR+1 in our case). Use the same ARR+1 "full scale" as setCaptureCompare() // so that get/set are consistent, and to avoid a divide by zero when ARR is 0. case PERCENT_COMPARE_FORMAT: - return_value = (CCR_RegisterValue * 100) / (LL_TIM_GetAutoReload(_timerObj.instance) + 1); + return_value = uint64_t(CCR_RegisterValue) * 100 / timerPeriodTicks(_timerObj.instance); break; case RESOLUTION_1B_COMPARE_FORMAT: case RESOLUTION_2B_COMPARE_FORMAT: @@ -1105,14 +1138,14 @@ uint32_t HardwareTimer::getCaptureCompare(uint32_t channel, TimerCompareFormat_ case RESOLUTION_14B_COMPARE_FORMAT: case RESOLUTION_15B_COMPARE_FORMAT: case RESOLUTION_16B_COMPARE_FORMAT: - return_value = (CCR_RegisterValue * ((1 << format) - 1)) / (LL_TIM_GetAutoReload(_timerObj.instance) + 1); + return_value = uint64_t(CCR_RegisterValue) * ((1U << format) - 1) / timerPeriodTicks(_timerObj.instance); break; case TICK_COMPARE_FORMAT: default : return_value = CCR_RegisterValue; break; } - return return_value; + return limitTimerValue(return_value, UINT32_MAX); } void HardwareTimer::setPWM(uint32_t channel, pin_size_t pin, uint32_t frequency, uint32_t dutycycle, callback_function_t PeriodCallback, callback_function_t CompareCallback) diff --git a/docs/HardwareTimer-library.md b/docs/HardwareTimer-library.md index 8112791fdd..855729bd09 100644 --- a/docs/HardwareTimer-library.md +++ b/docs/HardwareTimer-library.md @@ -16,10 +16,11 @@ __Example__: Each timer may provide several channels. All channels of the same timer share the same counter, prescaler, and overflow value, and therefore have the same period/frequency. Only their compare values, duty cycles, or capture events can differ. -> [!WARNING] -> For genericity purpose, HardwareTimer library uses all timers like a 16bits timer (even if some may be wider). +The configured tick period can use the native counter width. A 16-bit timer accepts up to 65536 ticks and a 32-bit timer up to 4294967296 ticks. The initial period remains 65536 ticks on both. The prescaler still supports factors from 1 to 65536. + +`setOverflow()` takes a `uint64_t` and `getOverflow()` returns a `uint64_t`. Existing calls that pass a 32-bit value still work. Store the result in a `uint64_t` when the period may exceed 32 bits. Update declarations that name either exact member-function type and rebuild code compiled against the old API. -This limits the directly configured counter period and compare values to the 16-bit range. Longer periods can often be obtained by increasing the prescaler. +Tick and microsecond requests above the hardware limit saturate. A zero-hertz request leaves the configuration unchanged, and frequencies above the timer clock select a one-tick period. On a 32-bit timer, microsecond and hertz requests select the smallest prescale factor whose counter period fits. A 16-bit timer retains the existing microsecond conversion and prescale factor selection for representable requests. Results are quantized to hardware ticks. At the maximum auto-reload value, PWM compare can reach one tick short of a full period. ## 2. API @@ -33,8 +34,8 @@ This limits the directly configured counter period and compare values to the 16- void setPrescaleFactor(uint32_t prescaler); // set prescaler register (which is factor value - 1) uint32_t getPrescaleFactor(); - void setOverflow(uint32_t val, TimerFormat_t format = TICK_FORMAT); // set AutoReload register depending on format provided - uint32_t getOverflow(TimerFormat_t format = TICK_FORMAT); // return overflow depending on format provided + void setOverflow(uint64_t val, TimerFormat_t format = TICK_FORMAT); // set AutoReload register depending on format provided + uint64_t getOverflow(TimerFormat_t format = TICK_FORMAT); // return overflow depending on format provided void setPWM(uint32_t channel, PinName pin, uint32_t frequency, uint32_t dutycycle, callback_function_t PeriodCallback = nullptr, callback_function_t CompareCallback = nullptr); // Set all in one command freq in HZ, Duty in percentage. Including both interrupt. void setPWM(uint32_t channel, uint32_t pin, uint32_t frequency, uint32_t dutycycle, callback_function_t PeriodCallback = nullptr, callback_function_t CompareCallback = nullptr); @@ -174,7 +175,7 @@ Then it is possible to configure *overflow* (also called rollover or update). Th For __output__ it correspond to period or frequency. -For __input capture__ it is suggested to use max value: 0x10000 to avoid rollover before capture occurs . +For __input capture__, configure the full period for the timer width to reduce rollovers between captured edges. > [!NOTE] > Configuration of *prescaler* is automatic when using method `setOverflow` with `format == MICROSEC_FORMAT` or `format == HERTZ_FORMAT`. @@ -183,12 +184,15 @@ For __input capture__ it is suggested to use max value: 0x10000 to avoid rollove > *overflow* is common to all channel. > [!NOTE] -> *Overflow* range: [1.. 0x10000] (Hardware register will range [0..0xFFFF]). +> *Overflow* in ticks ranges from 1 to 65536 on a 16-bit timer and from 1 to 4294967296 on a 32-bit timer. ARR stores this value minus one. __Example__: ```C++ timer.setOverflow(10000); // Default format is TICK_FORMAT. Rollover occurs after 10000 ticks (the counter runs from 0 to 9999) timer.setOverflow(10000, TICK_FORMAT); + // For a 32-bit timer, use the whole counter range: + // timer.setOverflow(uint64_t{1} << 32, TICK_FORMAT); + // uint64_t period = timer.getOverflow(TICK_FORMAT); timer.setOverflow(10000, MICROSEC_FORMAT); // 10000 microseconds = 10 milliseconds timer.setOverflow(10000, HERTZ_FORMAT); // 10 kHz ``` @@ -199,7 +203,7 @@ Then it is possible to configure *CaptureCompare* (channel specific CaptureCompa > *CaptureCompare* is for one channel only. > [!NOTE] -> *CaptureCompare* range: [0.. 0xFFFF] +> *CaptureCompare* in ticks ranges from 0 to 0xFFFF on a 16-bit timer and from 0 to 0xFFFFFFFF on a 32-bit timer. __Example__: ```C++ @@ -391,6 +395,4 @@ New optional parameter *destruct* has been added to *noTone* to decide whether t noTone(uint8_t _pin, bool destruct = false) ``` ## 6. Restriction -There is a special case where period is set to its maximum value 0xFFFF and 100% duty cycle is requested. -It is not possible to achieve this from hardware point of view (except changing mode to `TIMER_OUTPUT_COMPARE_FORCED_ACTIVE`). -In this specific case there will be 1 tick (the last one) which will be LOW. Then we lose only 1 tick out of 65535 => 99,998..% +When ARR is at the native maximum, a PWM 100% request would need a CCR one larger than ARR. CCR saturates at the native maximum, leaving the last tick low in PWM mode 1. Use `TIMER_OUTPUT_COMPARE_FORCED_ACTIVE` when the output needs to remain active. diff --git a/libraries/SrcWrapper/inc/HardwareTimer.h b/libraries/SrcWrapper/inc/HardwareTimer.h index 356e5c62c9..dd4668d9cb 100644 --- a/libraries/SrcWrapper/inc/HardwareTimer.h +++ b/libraries/SrcWrapper/inc/HardwareTimer.h @@ -227,7 +227,7 @@ class HardwareTimer { /** * @brief Configure hardwareTimer prescaler - * @param prescaler Prescaler factor + * @param prescaler Prescaler factor, limited to [1..65536] */ void setPrescaleFactor(uint32_t prescaler); /** @@ -243,6 +243,9 @@ class HardwareTimer { * immediately, but become effective at the next update event * (usually the next timer overflow). See setPreloadEnable() * for controlling this behaviour. + * Tick and time requests saturate at the hardware limit. Zero hertz + * leaves the configuration unchanged. Requests above the timer + * clock select a one-tick period. * @param overflow Overflow value, depends on format parameter * @param format Format of overflow parameter. If omitted default format * is Tick @@ -251,7 +254,7 @@ class HardwareTimer { * overflow * HERTZ_FORMAT: overflow is the frequency in hertz for overflow */ - void setOverflow(uint32_t overflow, TimerFormat_t format = TICK_FORMAT); + void setOverflow(uint64_t overflow, TimerFormat_t format = TICK_FORMAT); /** * @brief Retrieve overflow (rollover) value from hardware register * @param format Format of returned value. If omitted default format is Tick @@ -260,7 +263,7 @@ class HardwareTimer { * MICROSEC_FORMAT: return number of microsecondes for overflow * HERTZ_FORMAT: return frequency in hertz for overflow */ - uint32_t getOverflow(TimerFormat_t format = TICK_FORMAT); + uint64_t getOverflow(TimerFormat_t format = TICK_FORMAT); /** * @brief All in one function to configure PWM