Skip to content

Commit 16c23fa

Browse files
authored
Merge pull request #373 from soburi/improve_analog_write
core: arduino: analogWrite: Fix max value calculation
2 parents 04e105e + 4330b94 commit 16c23fa

File tree

1 file changed

+4
-7
lines changed

1 file changed

+4
-7
lines changed

cores/arduino/zephyrCommon.cpp

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

318318
void analogWrite(pin_size_t pinNumber, int value) {
319+
const int maxInput = BIT(_analog_write_resolution) - 1U;
319320
size_t idx = pwm_pin_index(pinNumber);
320321

321322
if (idx >= ARRAY_SIZE(arduino_pwm)) {
@@ -327,19 +328,15 @@ void analogWrite(pin_size_t pinNumber, int value) {
327328
}
328329

329330
_reinit_peripheral_if_needed(pinNumber, arduino_pwm[idx].dev);
330-
value = map(value, 0, 1 << _analog_write_resolution, 0, arduino_pwm[idx].period);
331+
value = CLAMP(value, 0, maxInput);
331332

332-
if (((uint32_t)value) > arduino_pwm[idx].period) {
333-
value = arduino_pwm[idx].period;
334-
} else if (value < 0) {
335-
value = 0;
336-
}
333+
const uint32_t pulse = map(value, 0, maxInput, 0, arduino_pwm[idx].period);
337334

338335
/*
339336
* A duty ratio determines by the period value defined in dts
340337
* and the value arguments. So usually the period value sets as 255.
341338
*/
342-
(void)pwm_set_pulse_dt(&arduino_pwm[idx], value);
339+
(void)pwm_set_pulse_dt(&arduino_pwm[idx], pulse);
343340
}
344341

345342
#endif

0 commit comments

Comments
 (0)