Skip to content

Commit 50f2057

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 bce8d7c commit 50f2057

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
@@ -398,6 +398,11 @@ int analogWriteResolution() {
398398

399399
#ifdef CONFIG_PWM
400400

401+
static uint32_t map64(uint32_t x, uint32_t in_min, uint32_t in_max, uint32_t out_min,
402+
uint32_t out_max) {
403+
return ((uint64_t)(x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min);
404+
}
405+
401406
void analogWrite(pin_size_t pinNumber, int value) {
402407
const int maxInput = BIT(_analog_write_resolution) - 1U;
403408
size_t idx = pwm_pin_index(pinNumber);
@@ -412,7 +417,7 @@ void analogWrite(pin_size_t pinNumber, int value) {
412417

413418
value = CLAMP(value, 0, maxInput);
414419

415-
const uint32_t pulse = map(value, 0, maxInput, 0, arduino_pwm[idx].period);
420+
const uint32_t pulse = map64(value, 0, maxInput, 0, arduino_pwm[idx].period);
416421

417422
/*
418423
* A duty ratio determines by the period value defined in dts

0 commit comments

Comments
 (0)