ArduinoCore-renesas icon indicating copy to clipboard operation
ArduinoCore-renesas copied to clipboard

AnalogWrite creates a PWM when value is 255

Open jpcornil-git opened this issue 1 year ago • 1 comments

On legacy arduino platforms, when analogWrite value is 255, you get a DC/HIGH output (aliased to digitalWrite HIGH), see:

https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring_analog.c#L110

While on UNO R4/renesas platform, 255 is converted to 255/256 and you get a PWM signal, see: https://github.com/arduino/ArduinoCore-renesas/blob/main/cores/arduino/analog.cpp#L819

To match behavior, value should either be normalized to 255 ((1 << _writeResolution) - 1) or aliased to a digitalWrite as well

jpcornil-git avatar Oct 25 '24 07:10 jpcornil-git

Workaround for this one is to use digitalWrite(pin, HIGH) (following a pinMode(pin, OUTPUT) to address #58) but it is not very clean

jpcornil-git avatar Oct 25 '24 12:10 jpcornil-git

This issue still appears to be unresolved, and it's causing the internal RGB LED on the Nano R4—which is connected as active low—not to turn off completely.

metehoca avatar Jul 30 '25 07:07 metehoca

Issue is probably simple to solve if you replace L817 of cores/arduino/analog.cpp:

    ptr->pulse_perc((float)value * 100.0 / (1 << _writeResolution));

with (with 8b resolution, 100% is 255 not 256):

    ptr->pulse_perc((float)value * 100.0 / (1 << _writeResolution - 1));

32b float arithmetic looks OK as long as _writeResolution is less than 17 (from 17, IEEE 23b mantissa can't represent (1 << _writeResolution - 1)* 100.0f without truncation leading to 99.9999... iso 100.0%). I quickly looked at the call stack pulse_perc/pulseWidth_raw/.../ and it should propagate to R_GPT_DutyCycleSet without rounding errors and that one seems to accept a value equal to the period that generates a steady '1'

jpcornil-git avatar Jul 30 '25 21:07 jpcornil-git

@jpcornil-git Good catch! thanks for pointing it out!

@metehoca I opened this PR #483, please give a spin with NanoR4 and let me know.

leonardocavagnis avatar Aug 01 '25 10:08 leonardocavagnis

@leonardocavagnis works like a charm!

metehoca avatar Aug 01 '25 10:08 metehoca