Skip to content

Commit 72ed78e

Browse files
author
Sergey Pluzhnikov
committed
[stm32] Timer fix: avoid arithmetic overflow in setPeriod
1 parent a672dd1 commit 72ed78e

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

src/modm/platform/timer/stm32/general_purpose.hpp.in

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,16 @@ public:
201201
{
202202
// This will be inaccurate for non-smooth frequencies (last six digits unequal to zero)
203203
const uint32_t cycles = duration.count() * SystemClock::Timer{{ id }} * Period::num / Period::den;
204-
const uint16_t prescaler = (cycles + std::numeric_limits<Value>::max() - 1) / std::numeric_limits<Value>::max(); // always round up
204+
uint16_t prescaler;
205+
if constexpr (sizeof(Value) > sizeof(uint16_t)) {
206+
// always round-up
207+
prescaler = (cycles + static_cast<uint64_t>(std::numeric_limits<Value>::max()) - 1) /
208+
std::numeric_limits<Value>::max();
209+
} else {
210+
// always round-up
211+
prescaler =
212+
(cycles + std::numeric_limits<Value>::max() - 1) / std::numeric_limits<Value>::max();
213+
}
205214
const Value overflow = cycles / prescaler - 1;
206215

207216
setPrescaler(prescaler);

0 commit comments

Comments
 (0)