Random Fade LED

I am trying to get an LED to fade up then off using a random number. I am very close to actually having it, but when the fade gets to its brightest, it then just goes back to zero. Below is the code i am trying to make work. Anyone have any suggestions on what I am doing wrong here.

int brightness = 0; // how bright the LED is int fadeAmount = 0; // how many points to fade the LED by long randNumber1; //adding randomizer to it

void setup() { // declare pin 9 to be an output: pinMode(9, OUTPUT); Serial.begin(9600); // if analog input pin 0 is unconnected, random analog // noise will cause the call to randomSeed() to generate // different seed numbers each time the sketch runs. // randomSeed() will then shuffle the random function. randomSeed(analogRead(0)); }

void loop() {

// set the brightness of pin 9: analogWrite(9, brightness); randNumber1 = random(2, 25); fadeAmount = randNumber1;

// change the brightness for next time through the loop: brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade: if (brightness == 0 || brightness == 255) { fadeAmount = -fadeAmount ; } // wait for 30 milliseconds to see the dimming effect delay(50); }

if (brightness == 0 || brightness == 255) {

What happens if brightness was 252, and it got incremented by 5?

If brightness is 0, why do you want to let it get smaller?

You need another value, integer, fadeSign that is either -1 or +1. The fadeAmount value should always be positive. brightness should always be "incremented" by fadeSign * fadeAmount.

The value for fadeSign should be positive until brightness exceeds 255, and should then be negative until brightness falls below 0.

I was actually using the fade option that came with the arduino software. I switched over to the “Fading” file and made some new changes and was able to make it work. See Below:

int ledPin = 9; // LED connected to digital pin 9
long randNumber1; //adding randomizer to it

void setup() {

Serial.begin(9600); // if analog input pin 0 is unconnected, random analog
// noise will cause the call to randomSeed() to generate
// different seed numbers each time the sketch runs.
// randomSeed() will then shuffle the random function.
randomSeed(analogRead(0));

}

void loop() {
randNumber1 = random(2, 25);
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=randNumber1) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

// fade out from max to min in increments of 5 points:
for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=randNumber1) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}

Thanks for the reply though. It got me thinking and helped get me on the right path.