Skip to content

Commit 3b5bf65

Browse files
committed
cores: arduino: analogWrite: Fix max value calculation
- Fixed input max value calculation (Needs to be -1 after shift) - Clamp calculations are performed first, eliminating cast Signed-off-by: TOKITA Hiroshi <tokita.hiroshi@gmail.com>
1 parent 9c6f3fe commit 3b5bf65

1 file changed

Lines changed: 4 additions & 7 deletions

File tree

cores/arduino/zephyrCommon.cpp

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,7 @@ int analogWriteResolution() {
391391
#ifdef CONFIG_PWM
392392

393393
void analogWrite(pin_size_t pinNumber, int value) {
394+
const int maxInput = BIT(_analog_write_resolution) - 1U;
394395
size_t idx = pwm_pin_index(pinNumber);
395396

396397
if (idx >= ARRAY_SIZE(arduino_pwm)) {
@@ -401,19 +402,15 @@ void analogWrite(pin_size_t pinNumber, int value) {
401402
return;
402403
}
403404

404-
value = map(value, 0, 1 << _analog_write_resolution, 0, arduino_pwm[idx].period);
405+
value = CLAMP(value, 0, maxInput);
405406

406-
if (((uint32_t)value) > arduino_pwm[idx].period) {
407-
value = arduino_pwm[idx].period;
408-
} else if (value < 0) {
409-
value = 0;
410-
}
407+
const uint32_t pulse = map(value, 0, maxInput, 0, arduino_pwm[idx].period);
411408

412409
/*
413410
* A duty ratio determines by the period value defined in dts
414411
* and the value arguments. So usually the period value sets as 255.
415412
*/
416-
(void)pwm_set_pulse_dt(&arduino_pwm[idx], value);
413+
(void)pwm_set_pulse_dt(&arduino_pwm[idx], pulse);
417414
}
418415

419416
#endif

0 commit comments

Comments
 (0)