Constant LED flicker while fading up/on and fading down/off.

Hello everybody. I've been working on a Steampunk Lantern project for a while, every thing's perfect in regards to the code. However, I would like to add a flickering effect to give it some more realism but everything I have been trying is uber glitchy. My idea is constant flickering, even while the LED fades on after a button press and when it fades off completely after another button press. Here's the code for toggling/fading the LED on and off after button presses:

reading = digitalRead(Switch);

if (reading == LOW && previous == HIGH && millis() - time > debounce) {
    
    if (state == 255) {
    while(state > 0) {
    state--;
    analogWrite(flame, state);
     delayMicroseconds(800);
    }
    }
    else if (state == 0) {
    while(state < 255) {
    state++;
    analogWrite(flame, state);
    delayMicroseconds(800);
    }
    }
     time = millis();  
}
    previous = reading;
  
    }

}

Me previous attempts ignored the fade on and off and simply flickers.

Any help would be appreciated! :slight_smile:

Kind regards

Lewis

I am having a hard time reading that sketch. Can you Auto Format, under the Tools menu option. Then send it again inside code tags. (in the forum editor, there is a button for that "#".

Could try using it with those LEDs that have a built-in "flicker effect"?
I've never used them...or have any idea how they respond to PWM...but I'd let you experiment for me! :stuck_out_tongue:

Can you better describe the effect that you're after?

Okay, first post fixed. My intentional effect is like that of a Lantern; you light it, it "fades up" but the flame is flickering as it fades up completely. The same principle applies when you extinguish the flame, it "fades off" but the flame is flickering as it fades completely off.

My initial idea was increasing the LED state using a percentage instead of a value between 0-255. So for example;

state++ (10%) So increase each state to a certain percentage (or a PWM value) and decrease that by 50% so we get a "flicker" while the LED is fading on
state-- (5%)
state++(20%)
state--(10%)
etc.

Then, when we reach 100% or a PWM value of 255 we go to a loop:

state-- (50%) or a PWM value 122

Then we increase that value back to 100% or a PWM value of 255

state++(100%) or a PWM value of 255

And then back to 50% or a PWM value of 122

After a button press, the LED starts to fade/flicker off. This time, we are going in the opposite direction:

state++ (100%)
state-- (50%)
state++(80%)
state--(40%)
etc.

Hopefully I've explained it well, demonstrations and descriptions are not my forte.

Kind regards

Lewis

I am not sure what you put inside the code tags, but I don't think it is a sketch that could compile.
Please give us the formatted sketch.

Sorry for the confusion. It's not supposed to be a sketch, just a more in depth explanation of what I'm trying to achieve.