Simple millis timing issue - results not as expected

Hello everyone,

I cannot figue why I am not getting the expected results from my simple code. The program has a simple switch case 0 & 1, to change LED patterns. After case 0 runs for 15 sec, it switches to case 1. Case 1 SUPPOSED to run for 3 sec, then go back to case 0. But it runs for the previously mention 15 sec. I can't figure out why

{
  t = millis();
  
  if ((t - prevTime) > 15000) // Every 15 seconds change mode...
    {      
      if (mode == 0) // In mode 0 ?
      {
      mode++; // go to second mode
      pixels.setBrightness(0);
      }
  else if ((t - prevTime) > 5000) // Every 5 seconds go back to 1st mode...
    {
      if (mode == 1) // In mode 1?
      {
      mode--; // go to first mode
      pixels.setBrightness(0);
      }
    }
    else
    {
      ; // do nothing, just a place holder
    }
  
    prevTime = t;
  }
}

The program runs as expected except the timing of case 1 is not correct. Can anyone spot what I am doing wrong? I added the outermost brackets here to show it is still part of another program.

Thanks,

Brian

The else if part is inside the if ((t - prevTime) > 15000) part, so it gets evaluated only after 15 seconds.

I think you need two different versions of prevTime - one for each period and each of them should be reset when the appropriate time expires.

And what @Shpaget says - which I had not spotted.

...R

Thanks for the response. I see now that it was blocking the other statements, so here I simplified it even further:

  t = millis();
  
  if ((t - prevTime) > 15000 && mode == 0) // Every 15 seconds change mode...
      
      {      
      mode++; // go to second mode
      pixels.setBrightness(0);
      }
    
  if ((t - prevTime) > 5000 && mode == 1) // Every 5 seconds go back to 1st mode...
   
      {
      mode--; // go to first mode
      pixels.setBrightness(0);
      }
    
    prevTime = t;
  }

It should just switch back and forth after meeting the criteria. But it still refuses to go to the second mode at all.

If prevTime is greater than 15000 in the first test it will certainly be greater than 5000 in the second one and switch the mode back to 0. Update prevTime each time you change mode.

  t = millis();
  
  if ((t - prevTime) > 15000 && mode == 0) // After 15 seconds in mode 0...
      
      {      
      mode++; // go to mode 1
      pixels.setBrightness(0);
      prevTime = t; // re-start timer
      }
    
  if ((t - prevTime) > 5000 && mode == 1) // After 5 seconds in mode 1...
      {
      mode--; // go to mode 0
      pixels.setBrightness(0);
      prevTime = t; // re-start timer
      }
  }

thelastosirus:
Thanks for the response.

You have not created two separate versions of prevTime, as I suggested earlier. You need a prevTime15 and a prevTime5 (or something equivalent).

...R