Set led brightness and fade to set value without delay (PWM)

Hey guys,

First of all, I want to say that I appreciate for taking from your personal time to answer to my question. Anyway here's the issue.

I want to a fade the led brightness to a set value without delay. This is code:

**'dim' is the actual led brightness
**'set_value ' is the brightness level set through serial
PS: The serial function has been omitted intentionally.

//////////////////////////

int fadeAmount = 1; // how many points to fade the LED by
unsigned long currentTime;
unsigned long loopTime;
int set_value = 115; // the brightness level set from serial
int dim = 0;

void setup()
{
currentTime = millis();
loopTime = currentTime;
}

void loop()
{
currentTime = millis();
if(currentTime >= (loopTime + 50))
{
if(set_value < dim)
{
fadeAmount = -fadeAmount;
dim+=fadeAmount;

}
if(set_value > dim)
{
fadeAmount = 1;
dim+=fadeAmount;
}
loopTime = currentTime; // Updates loopTime
}
}

/////////////////////////

What am I doing wrong? :astonished:

Try ...

if (set_value <  dim)
{
    dim -= fadeAmount;
}
if (set_value >  dim)
{
    dim += fadeAmount;
}

The code would be a bit easier to understand if you used a better name for dim. Maybe currentLEDValue.

And please use code tags when you post code :slight_smile: (the "#" button above the row of smileys).

Regards

Ray

Thanks for the tip... I'm kinda new to this forum. :~ I'll do that next time.
Regarding the code, I'll try that.

Take look at blink without delay and look and how the timing is handled there.

Mark

Thank you Mark and Ray. You've been very helpful.
I figured it out!
XD