Skip to main content
removed the wrong part of the code.
Source Link
ElectronSurf
  • 814
  • 4
  • 17
  • 44

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();
        }
        else{
            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?

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();
        }
        else{
            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?

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?

Source Link
ElectronSurf
  • 814
  • 4
  • 17
  • 44

PWM delay without blocking the code

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();
        }
        else{
            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?