0

I want my LED to turn on gradually without using the delay() function and blocking the code.

Here's the code i came up with:

int led_pin = 6;
unsigned long millisTimer = 0;
int PWMdelay = 5000;
int condition = 0;
int i = 0;
void setup() {
 pinMode(led_pin, OUTPUT);
}
void loop() {
 if(condition == 1){
 if ((millis() - millisTimer) > PWMdelay){
 if(i<255){
 i++;
 millisTimer = millis();
 }
 }
 analogWrite(led_pin, i);
 }
}

Is this the "right way" of slowing the PMW duration from 0 to 255 or there are alternative/better/easier ways?

asked Jun 23, 2019 at 14:37
8
  • 1
    Seems ok for fade in timer. Why are you doing the else with i--? Do you want to fade out the LED after the fade in? That does not work this way, since it will only vary between 254 and 255. Commented Jun 23, 2019 at 14:44
  • 1
    the Fade example in IDE uses delay, but shows how to go up and then down. and put millisTimer = millis(); outside if-else Commented Jun 23, 2019 at 14:46
  • 1
    From my personal definition, the "right way" is a way that works. So, does it work? Your approach is a common way to do tasks without delay (like in the BlinkWithoutDelay example) Commented Jun 23, 2019 at 14:46
  • 1
    see the Fade example and the BlinkWithoutDelay example in IDE Examples menu Commented Jun 23, 2019 at 14:49
  • 1
    That's fine, I do it the same way Commented Jun 23, 2019 at 16:42

1 Answer 1

3

Here is my take at this - I've followed the example code mentioned by other members and here is "FadeWithoutDelay"


const int ledPin = 11;
unsigned long previousMillis = 0; // will store last time LED was updated
const long interval = 100; // fade interval (milliseconds)
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
void setup() 
{
 pinMode(ledPin, OUTPUT); // set the digital pin as output:
}
void loop() 
{
 unsigned long currentMillis = millis();
 if (currentMillis - previousMillis >= interval) 
 {
 previousMillis = currentMillis; // save the last state
 analogWrite(ledPin, brightness); // Set the brightness
 brightness = brightness + fadeAmount; // change the brightness for next time through the loop
 // reverse the direction of the fading at the ends of the fade:
 if (brightness <= 0 || brightness >= 255) 
 {
 fadeAmount = -fadeAmount;
 }
 }
}
answered Jun 24, 2019 at 11:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.