Limitations of Hardware PWM

 

The pins that can do hardware Pulse Width Modulation are pins 4, 9, 10, 12, 13, 14, and 19. These are the pins that are connected to the bits 2 and 6 on Port 1, and bits 1, 2, 4, and 6 on Port 2.

This can get a bit confusing, with the two names for each LED. Fortunately, there are convenient names for the pin numbers that map them back to the ports and bits. Instead of saying

        analogWrite( 4, 20 );

we can say

        analogWrite( P1_2, 20 );

so we can think in terms of Port 1 Bit 2 instead of trying to remember which pin is connected to that bit. This is convenient because the pins on the board are not numbered, but they are labeled with the port number and the bit number. So instead of counting, we can just connect the wire to the pin with the right label.

Hardware Pulse Width Modulation is done using timers inside the computer chip. The chip has three timers. so only three different brightness levels can be controlled at once.
 
The timers are limited as to which pins they can control. The first timer can control P1_2, P1_6, and P2_6. If you have three LEDs, one connected to each of those pins, respectively, then they will all be under the control of the same timer. This makes analogWrite() do an unexpected thing: writing to either pin changes all three of them.
 
The same goes for the second timer, which connects to P2_1, and P2_2. The analogWrite() to either one controls both at the same time.
 
The third timer connects to P2_4 and P2_5. analogWrite() to either changes both.
 
Only analogWrite() has this problem, because digitalWrite() doesn't use the timers, so it can control one LED at a time just fine.