Fade using Millis

Hi,

I'm new when it comes to writing code, though have a reasonable understanding and some experience with circuitry and electronics. Wondering if anyone could help with part of a new project;

I'm trying to use the 'Millis' to fade and led up and down on a pwm pin but i'm having some difficulty, what happens is that the led fades up and down cleanly 2 or 3 times, then begins to 'stutter' and after a little while gets stuck at full brightness and flickers then seems to repeat the cycle. What am I doing wrong?!:

int led = 45; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
unsigned long previousMillis = 0;
unsigned long interval = 30;

void setup() {
pinMode(led, OUTPUT);
}

void loop() {
unsigned long currentMillis = millis(); // grab current time
analogWrite(led, brightness); // set the brightness of ledPin:

if (currentMillis - previousMillis >= interval){
brightness = brightness + fadeAmount; // change the brightness for next time through the loop:
previousMillis = millis();
}
if (brightness <= 0 || brightness >= 255) { // reverse the direction of the fading at the ends of the fade:
fadeAmount = -fadeAmount;
}
}

When you test to see if the brightness is <0 or >255, although you reverse direction, you still let those <0 or >255 values through.

Becasue brightness is an int, that's legit as far as the value is concerned, but in the case of say 256, it sets the next left bit in the bye to 1, and the 8 rightmost ones which were 1111 now go straight back to 0.

So when you do those tests, you need need to set brightness = 0 if it was <0, and to 255 if it was > 255.

if (brightness <= 0 )
  { // reverse the direction of the fading at the ends of the fade:
    brightness = 0;
    fadeAmount = -fadeAmount;
  }
    if (brightness >=255 )
  { // reverse the direction of the fading at the ends of the fade:
    brightness = 255;
    fadeAmount = -fadeAmount;
  }

Ah, Amazing! That makes total sense.

Thanks manor_royal.