You could use the analogWrite() function and connect the LED to a pin that supports pwm. (For this: see you Sketchbook: Examples->Analog->Fading)
Or if you don't want to use pwm, you can try the following code:
uint8_t ledPin = 8;
uint8_t brightness;
uint8_t counter;
void setup()
{
pinMode(ledPin, OUTPUT);
}
void loop()
{
for(brightness = 0; brightness<255; brightness++)
{
for(counter = 0; counter <255; counter++)
{
digitalWrite(ledPin, counter<brightness);
}
delay(1);
}
for(brightness = 255; brightness>0; brightness--)
{
for(counter = 0; counter <255; counter++)
{
digitalWrite(ledPin, counter<brightness);
}
delay(1);
}
}
the counter variable is used to divide time into 256 time slots. In each time slot the LED can be on or off.
Example: brightness = 100
then the led is on for the first 100 time slots and off for the remaining 155 time slots.
By increasing brightness (outer loop) from 0 to 255 and then decreasing it, the LED is fading.
delay(1); makes sure that this fading isn't too fast. If you need a slower fading, simply change the delay value.