Use millis instead of Delay

Hey guys, I´m still automating my appartment with Blynk :v:
Now, the illumination from the stairs have to believe in it.
Until now it works like this: When the PIR sensor detect someone, al LED-strip under the stairs fade slowly up. Later in additional I want get a message over Blynk that it got on. Until now it fades up with a delay inside the code which I needed to remove. My problem´s that it is inside a for-loop. Is there a possibility to remove and replace it with millis() ?

int ledPin = D5;
int brightness = 0;

void guydetected() {
  for (int i = -90; i < 90; i++) {
    float angle = radians(i);
    brightness = (255 / 2) + (255 / 2) * sin(angle);
    Serial.println(brightness);
    analogWrite(ledPin, brightness);
    delay(30);
  }

Hi,

You could have a timer that you call every 30ms to do a single step of the fading each time.

Here’s an example of Timer:

And some partial code that hopefully helps:

void setup()
{  //Add the following line
timer.setInterval(30L, FadeLEDs);
}

int FadePosition = -90;
bool MotionDetected;

void FadeLEDs()
{
  if (MotionDetected)
  {
     if(FadePosition < 90)
     {
       FadePosition++;
       float angle = radians(FadePosition);
       brightness = (255 / 2) + (255 / 2) * sin(angle);
       Serial.println(brightness);
       analogWrite(ledPin, brightness);
     }
  }
}

First of all: Thanks for your quick reply.
Second: error in line 16. (‘i’ was not declared in this scope)
If now I declare ‘i’ as an integer, equal if it´s -90 or 90 for exampe, I usually get a fix brightness value in Serial Monitore :confounded:

#include <SimpleTimer.h>

int i = 50;
int brightness = 0;
int ledPin = D5;
int FadePosition = -90;
bool MotionDetected=1;

SimpleTimer timer;

void loop() {
  timer.run();

}



void setup()
{  //Add the following line
timer.setInterval(30L, FadeLEDs);
Serial.begin(9600);
}



void FadeLEDs()
{
//  if (MotionDetected)
//  {
     if(FadePosition < 90)
     {
       FadePosition++;
       float angle = radians(i);
       brightness = (255 / 2) + (255 / 2) * sin(angle);
       Serial.println(brightness);
       analogWrite(ledPin, brightness);
     }
//  }
}

I commented the if-condition only to test the sketch easier. :wink:
Serial Monitor shows me that the value of brightness is constant 224

I think you need to replace i with FadePosition

Also, does this give a brightness value of 0-255, or 0-1023?

Pete.

1 Like

Pete you are great!
I replaced i with FadePosition, now it fades up :see_no_evil: