Skip to content

Commit 382ce7c

Browse files
Raffael Rostagnokartben
authored andcommitted
drivers: mcpwm: esp32: Fix duty rounding
Duty value in the driver is calculated from timer cycles, which can introduce precision loss when converting from pwm_set() to pwm_set_cycles(). To avoid truncating values with a fractional part ≥ 0.5 and further drifting the effective duty, round the computed duty to the nearest integer. Signed-off-by: Raffael Rostagno <[email protected]>
1 parent 98b0065 commit 382ce7c

File tree

1 file changed

+1
-3
lines changed

1 file changed

+1
-3
lines changed

drivers/pwm/pwm_mc_esp32.c

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -252,9 +252,7 @@ static int mcpwm_esp32_set_cycles(const struct device *dev, uint32_t channel_idx
252252
return ret;
253253
}
254254

255-
double duty_cycle = (double)pulse_cycles * 100 / (double)period_cycles;
256-
257-
channel->duty = (uint32_t)duty_cycle;
255+
channel->duty = DIV_ROUND_CLOSEST((uint64_t)pulse_cycles * 100ULL, period_cycles);
258256

259257
channel->inverted = (flags & PWM_POLARITY_INVERTED);
260258

0 commit comments

Comments
 (0)