I'm trying to make two leds blink at the same time but when one of them is lightins the other one is fading.
Everything start fine buth after 30 seconds it starts to work wrongly. Do you know what I´m doing grong?
Here is what I'm doing:
int led = 9;
int luz = 13;
int darkness = 0;
int fadeAmount = 5;
int brightness = 255;
unsigned long previousMillis = 0;
const long interval = 20;
The range of values for the analogWrite() function are 0 to 255. You only need one brightness variable. Use 255-brightness for the other analogWrite() value.
I'm starting with Arduino and I was trying to make two leds blink at the same time, but while one of them is ligthing the other one is fasding. Everything stars fine buth after a minute both leds start to make some weird things and in the one one of them just fades and the other one just lights. Here is the code:
int led = 9;
int luz = 13;
int darkness = 0;
int fadeAmount = 5;
int brightness = 255;
unsigned long previousMillis = 0;
const long interval = 20;
This is entirely a programming problem.
Let's say this is the 50th iteration of this loop. Fadeamount is 5, brightness is 5, darkness is 250. What happens?
darkness = darkness + fadeAmount;
// darkness is now 255
if (darkness == 0 || darkness == 255) {
fadeAmount = -fadeAmount ;
// fadeamount is now -5
}
analogWrite(luz, brightness);
brightness = brightness - fadeAmount;
// brightness is now 10
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
}
So when darkness is 255, brightness is 10 instead of 0. Why? because you reverse the fade amount before computing brightness.
Now, what will happen after that? Well, brighness will hit 255 after another 49 iterations, but darkness will be 10 at that stage. The fade will reverse, but they'll remain off by ten. Then darkness will go up to 255 again, but once again the reverse will happen before the computation for brightness gets redone. So darkness will be 255, brightness will be 20 - off by another 10. It will just get worse and worse - which is exactly behavior you are seeing.