Understanding the fade without delay();

hey,

so i have a perfectly functioning loop, but im curious...

void loop() {
  byte interrupts = adxl.getInterruptSource(); // SECTION A

  unsigned long currentMillisLeds = millis();
    if (currentMillisLeds - previousMillisLeds >= intervalLeds) {
    previousMillisLeds = currentMillisLeds; // SECTION B

    
  if (xa < sensitivity) le -= fadeOut;  if (xa > sensitivity) le += fadeIn; if (le<0) le=0; if (le>255) le=255; state=1;
 
//state=1; //showLeds();


  } // end of timed loops // SECTION C

serialText(); // SECTION D

ok, in the above cut out section from my code, i have 4 sections;

A, precedes the timed loop (lets say this loop is 5000ms)
B, is in the timed loop
C, is the end of the timed loop
D, is outside the loop

will my code run through this super super super fast, and;
only trigger the section B if the parameters are met (every 5000ms), but sections A and D are called in order...

i.e.
A, wait for 5000ms, run D

or will the system be more like

ACDACDACDACDACDACDACDACDA (a thousand times a second) and when an actual 5000ms are detected, B will run?

therefore;

if my sensor is constantly checking variables, but will only act on them when the parameters (5000ms) are active?

Of course, D will run every time through loop(). It's not inside the if check for timing. But I take no responsibility for that assertion, unless you post your entire sketch. So most of the time you will have:

ADADADADADADADAD....

"C" didn't seem to do anything, so I ignored it.

yeah, that's what i thought... thanks for clarifying!

unfortunately though... that's not whats wrong with my sketch! :slight_smile:

if (xa < sensitivity) le -= fadeOut;  if (xa > sensitivity) le += fadeIn; if (le<0) le=0; if (le>255) le=255;

Alternatively:

if (xa < sensitivity) 
  le -= fadeOut;  
else if (xa > sensitivity) 
  le += fadeIn; 

le = constrain(le, 0, 255);

But this is just showing off and acheives nothing:

le = constrain(le + (xa < sensitivity ? -fadeOut : xa > sensitivity ? fadeIn : 0), 0, 255);

because the compiler will optimise it all down to the same thing.

Also this:

   if (currentMillisLeds - previousMillisLeds >= intervalLeds) {
    previousMillisLeds = currentMillisLeds; // SECTION B

This can potentially make your cycle "drift" a bit, if your code takes more than a millisecond to run on if it runs juuuust on the millis() tick. When milliseconds matter, to keep the timing consistent:

   if (currentMillisLeds - previousMillisLeds >= intervalLeds) {
    previousMillisLeds += intervalLeds; // SECTION B

:o i'm not sure my millis() are required to be that accurate... but hey, you never know!

and to be fair, it took me ages to work out le < o le > 255... the constrain function is a much more elegant way of showing it.

thanks!