Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
213 changes: 123 additions & 90 deletions cores/arduino/stm32/HardwareTimer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint32_t>(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};

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -1073,21 +1104,23 @@ 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()
// call) and, in Input Capture mode, whenever the last captured edge
// 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:
Expand All @@ -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)
Expand Down
Loading
Loading