digitalWrite(): Why turnOffPWM?

Hello,
I have a question that's been bothering me for a while. In the digitalWrite() library code (ie, wiring_digital.c, Arduino 1.0.5), I see this:

    // If the pin that support PWM output, we need to turn it off
    // before doing a digital write.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

The question is, why does it do that? I presume that the programmer who is performing PWM on an output would not be wanting to do a digitalWrite(), but if they goof up... well, is it really the responsibility of the library to try and interpret the user's mistakes, and compensate for them?

I also note that there has been some movement to optimize digitalWrite(), but I wonder what that stuff was doing in there in the first place?

Thanks.

GreyGnome:
The question is, why does it do that? I presume that the programmer who is performing PWM on an output would not be wanting to do a digitalWrite(), but if they goof up... well, is it really the responsibility of the library to try and interpret the user's mistakes, and compensate for them?

Arduino is made for the noobs, so most likely that was done with intent to create a fool-proof digitalWrite function.

But for that reason "digitalWrite" with PWM pins takes always one microsecond longer execution time than with non-PWM pins, whether PWM was on or not before calling digitalWrite.

Thanks. I thought I was missing something really important. I probably am, but it's not what I thought it was! :slight_smile: