Schematic

Code

In the setup() function of the code below, a for() loop is used to assign digital pins 2-13 of the Mega as outputs.

Next, in the loop() function of the program below, a trio of nested for() loops are used.

The first of these loops,

for (int thisPin =lowestPin; thisPin <= highestPin; thisPin++)

moves through each of the LEDS one by one, from the lowest pin to the highest. Before this loop is allowed to move from one pin to the next, two things must be accomplished. First, you brighten the individual LED through these lines of code:

With each pass through the loop above, the variable brightness increases by one point, and that value is written to the pin currently selected to the main loop. One that pin reaches the maximum PWM value (255), the following loop kicks in:

This loop subtracts a point from the brightness variable, dimming the LED back down to 0. Once zero is reached, the main for() loop kicks in, and the program moves on to the next LED pin, repeating all the steps mentioned above.

/*
Mega analogWrite() test

This sketch fades LEDs up and down one at a time on digital pins 2 through 13.
This sketch was written for the Arduino Mega, and will not work on previous boards.