Skip to content

Commit 6fabb62

Browse files
authored
Merge pull request #428 from gbr1/analogWrite-fix
zephyrCommon: fixs analogWrite overflow
2 parents 147ea1c + 85747f7 commit 6fabb62

1 file changed

Lines changed: 6 additions & 1 deletion

File tree

cores/arduino/zephyrCommon.cpp

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,11 @@ int analogWriteResolution() {
338338

339339
#ifdef CONFIG_PWM
340340

341+
static uint32_t map64(uint32_t x, uint32_t in_min, uint32_t in_max, uint32_t out_min,
342+
uint32_t out_max) {
343+
return ((uint64_t)(x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min);
344+
}
345+
341346
void analogWrite(pin_size_t pinNumber, int value) {
342347
const int maxInput = BIT(_analog_write_resolution) - 1U;
343348
size_t idx = pwm_pin_index(pinNumber);
@@ -357,7 +362,7 @@ void analogWrite(pin_size_t pinNumber, int value) {
357362
_reinit_peripheral_if_needed(pinNumber, arduino_pwm[idx].dev);
358363
value = CLAMP(value, 0, maxInput);
359364

360-
const uint32_t pulse = map(value, 0, maxInput, 0, arduino_pwm[idx].period);
365+
const uint32_t pulse = map64(value, 0, maxInput, 0, arduino_pwm[idx].period);
361366

362367
/*
363368
* A duty ratio determines by the period value defined in dts

0 commit comments

Comments
 (0)