(not sure if this has been discussed in the past)
Currently with analogWrite() if you pass a value of 0 you get a LOW and if you pass 255 you get a HIGH
and any value in between you get PWM.
The question is how to handle non pwm pins.
Currently the code will set the pin to LOW for any values less than 128 and HIGH for any values above 127.
based on this code in wiring_analog.c
case NOT_ON_TIMER:
default:
if (val < 128) {
digitalWrite(pin, LOW);
} else {
digitalWrite(pin, HIGH);
}
While I am very mindful of backward compatibility and always want to try to preserve it, I'm curious
on peoples thoughts on this existing behavior.
While it seems logical and useful at first, I find it very unhelpful in some real world situations.
In some cases it would be preferred that the code not attempt to "dim" half way through but
rather simply keep the pin HIGH for all values other than 0 as "dimming" (pwm) is simply not supported
on that pin.
For example, if using a pin to control a backlight on a lcd.
If the user writes code that supports dimming of the backlight, then the current behavior causes issues
because the sketch doesn't really know (and shouldn't really have to know) whether the pin supports pwm.
So now if the sketch asks for half brightness (which might be a value of 127) then the backlight is off.
The sketch has no way of knowing.
In this situation it would preferred that the pin remain high.
This extends to libraries as well. For example, suppose a library is trying to implement the
lcd 1.0 Arduino Playground - LCDAPI
The setBacklight() api call is defined to dim the backlight if it can but if it can't then it is full
bright until it is "off" with a value of 0.
To implement this kind of thing is very messy given the way the analogWrite() API functions today.
It may just be me but I was surprised the first time I ran into this as I saw the LED on the
arduino go off half way through the pwm values. I had to look up that it wasn't a pwm pin and
then look at the analogWrite() code to see that non pwm pins turn off half way through.
I was expecting a non pwm to not "dim" and stay on vs turn off half way through as staying on seemed
more logical/natural to me when pwm can't be done.
My suggestion would be to alter the analog_write() code to leave the pin HIGH until a value of 0
is specified for non pwm pins by changing the code to this:
default:
if (val) {
digitalWrite(pin,HIGH);
} else {
digitalWrite(pin, LOW);
}
This would change the behavior to leave the pin HIGH until it turned off with a 0
on non PWM pins which ensures that the output is not turned off for half the pwm values.
But this has backward compatibility issues as it is changing behavior.
So my questions are:
What do other folks think of this?
Have you seen real world cases where the existing behavior (pin LOW for values 127 and below) was needed
or preferred over leaving the pin HIGH for all values other than 0?
--- bill