Skip to content

Commit d43e5d0

Browse files
gbr1soburi
authored andcommitted
zephyrCommon: fixs analogWrite overflow
Co-Authored-by: Giovanni Bruno <g.bruno@arduino.cc> Signed-off-by: TOKITA Hiroshi <tokita.hiroshi@gmail.com>
1 parent f3f9dd5 commit d43e5d0

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

cores/arduino/zephyrCommon.cpp

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

395395
#ifdef CONFIG_PWM
396396

397+
static uint32_t map64(uint32_t x, uint32_t in_min, uint32_t in_max, uint32_t out_min,
398+
uint32_t out_max) {
399+
return ((uint64_t)(x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min);
400+
}
401+
397402
void analogWrite(pin_size_t pinNumber, int value) {
398403
const int maxInput = BIT(_analog_write_resolution) - 1U;
399404
size_t idx = pwm_pin_index(pinNumber);
@@ -408,7 +413,7 @@ void analogWrite(pin_size_t pinNumber, int value) {
408413

409414
value = CLAMP(value, 0, maxInput);
410415

411-
const uint32_t pulse = map(value, 0, maxInput, 0, arduino_pwm[idx].period);
416+
const uint32_t pulse = map64(value, 0, maxInput, 0, arduino_pwm[idx].period);
412417

413418
/*
414419
* A duty ratio determines by the period value defined in dts

0 commit comments

Comments
 (0)