// fade in
for (int fadeValue = 0 ; fadeValue <= 50; fadeValue += 5) {
while (currentMillis - previousMillis < interval); // an empty loop, equivalent to using delay()
analogWrite(ledPin, fadeValue);
previousMillis = currentMillis;
}
Do you see the difference, and why your previous attempt did not work?
But both my suggested change and your attempt are pointless. You might as well use delay(). Both are still "blocking code" and won't allow the Arduino to perform other tasks while the fading is going on.
In terms of "blocking code", do you have any sugestions on fade in & out with non-blocking code? Since I do need my Arduino to perform others tasks (e.g. use the remote control to run the stepper motor at the same time. )
Also, I just tried the code you suggested. But the outcome seems to be the same. The led still didn't light up. Maybe I misunderstood something. I would really appreciate it if you could explain a little bit more. Thank you so much.
int ledPin = 5;
unsigned long previousMillis = 0;
const long interval = 300;
void setup() {}
void loop() {
unsigned long currentMillis = millis();
// fade in
for (int fadeValue = 0 ; fadeValue <= 50; fadeValue += 5) {
while (currentMillis - previousMillis < interval);
analogWrite(ledPin, fadeValue);
previousMillis = currentMillis;
}
// // fade out
// for (int fadeValue = 50 ; fadeValue >= 0; fadeValue -= 2) {
// while (currentMillis - previousMillis < interval);
// analogWrite(ledPin, fadeValue);
// previousMillis = currentMillis;
// }
} //loop
Your code is using a for-loop to control fadeValue. To make the fading happen slowly and smoothly, so the fading effect can be seen by the eye, the for-loop must run slowly, by using either millis() or delay(). This makes the for-loop into blocking code. It's ok to have for-loops and while-loops in non-blocking code provided those loops run very quickly. But you need the for-loop to run slowly, which makes it blocking code. Therefore you cannot use a for-loop to control the value of fadeValue.
But it is not fixed yet, your code will not be able to perform other tasks while the led is fading. My point is that simply using millis() instead of delay() does not fix that problem.