Hi,
When I try to fade an LED using the following code, a random flash sometimes happens at the beginning of the cycle, as if the LED has been set to 255 instead of 1:
Original Code:
int led = 11;
int brightness = 0;
void setup()
{
pinMode(led, OUTPUT);
}
void loop()
{
if(brightness >= 256) //checks if brightness has passed 255, resets to 0
{
analogWrite(led, 255);
brightness = 0;
}
analogWrite(led, brightness);
if(brightness == 0)
{
delay(1000); //LED off for 1 second
}
brightness+=1; //increment brightness
delay(20);
}
This only happens occasionally - (watch a video of it on YouTube)
However when the brightness variable is continually incrementing and is not reset to zero, this does not happen - analogWrite() "overflows" back to zero when it reaches 256 or when it is given any multiple of 256. ie. analogWrite(led, 1024) sets led to 0.
Modified Code:
int brightness = 0;
int led = 11;
void setup()
{
pinMode(led, OUTPUT);
}
void loop()
{
analogWrite(led,brightness);
if((brightness == 0) || ((brightness%256) == 0)) //if brightness is at zero or is
{ // a multiple of 256, delay of 1 second
delay(1000);
}
else
{
delay(20); // otherwise, short delay to slow down fade rate
}
brightness++; //increment brightness
}
I have also tried:
- Changing board (to another UNO)
- Changing LED pin from 11 to 3
- Using a 12V power supply instead of USB (sometimes USB supply causes malfunctions)
So I am assuming that this is not a hardware problem, but a software problem. Any ideas why resetting brightness to zero would cause a flash to sometimes occur?