Timers, PWM and analogWrite

Can someone explain why, in the attached sketch, it only works as it is intended (hi, medium, hi, medium…) when the “redLED” (pin11) in lines 41 and 46 is written to?

If I change the statements in lines 41 and 46 to either “greenLED” (pin 9) or “blueLED” (pin 10), the analogWrite statement acts like digitalWrite. i.e. Any PWM less than 255 manifests as off.

All three of these pins are labeled PWM pins. Are the timers conflicting with the PWM? Any way around this?

Thanks for the help. -Scott

Test_AnalogWrite.ino (2.55 KB)

Pin 11 PWM is controlled by timer 2. PWM for pins 9 and 10 is controlled by timer 1. Timer 0 affects millis(), micro(), and delay(...).

I would guess that your use of timers 0 and 1 is not compatible with your use of pins 9 and 10 but I don't understand the finer details.

There are some libraries that may help you out, or you could choose some other pins.

When you analogWrite() to pin 9, you change the value of OCR1A, and that changes the way that Timer1 operates in CTC mode. The description of what you're trying to do, and what you're seeing instead, is a bit sketchy. But, with what we know, I suspect that this strategy wont work for what you hope to accomplish.

If you want to continue with this, you might consider using one timer for timing, and one for PWM.