Wait between fades

hello! I have a problem - I want my led to fade in and out and then wait two seconds between fading. I've tried to use delay and other things, but none seems to work. If I use delay, it justs messes up the fade, makes it longer or quicker. Can you help me out? :slight_smile:

Here's my code:

int value;
int ledpin = 5;
long time=0;

int period = 2000;

void setup()
{

}

int fade() {

time = millis();
value = 128+127cos(2PI/period*time);
analogWrite(ledpin, value);

}

void loop()
{
fade();

// i want a delay here, but it aint working!

}

Try adding a boolean flag that gets set to true when the fade has gone up and then down.
When the flag is true, add your two second delay.
Avoid using the delay() function. See the sticky at the top of the main page on how to use millis() for timing.

Here is an illustration of a simple state machine to fade up, fade down and delay using no delay(). See the millis() guide.

int value;
const byte ledpin = 5;
unsigned long time = 0;

byte fadeIncrement = 1; 
unsigned long fadeTime = 10;  //time between fade increments
unsigned long lastFadeTime = 0; 
unsigned long lastDelayTime = 0;
unsigned long period = 2000; // delay between fades

byte fadeState = 0; // 0 = fade up, 1 = fade down, 2 - delay

void setup()
{
   Serial.begin(115200);
   pinMode(ledpin, OUTPUT);
   digitalWrite(ledpin, LOW);
}

void fadeUp()
{
   // increment if it is time to do so
   if (time - lastFadeTime >= fadeTime) 
   {
      lastFadeTime = time;
      value = value + fadeIncrement; // repalce with your formula
      analogWrite(ledpin, value);
      //finished up, set up for next state
      if (value >= 255)
      {
         lastFadeTime = time;
         fadeState = 1;
      }
   }
}

void fadeDown()
{
   // decrement if it is time to do so
   if (time - lastFadeTime >= fadeTime)
   {
      lastFadeTime = time;
      value = value - fadeIncrement; // replace with your formula
      analogWrite(ledpin, value);
      //finished down, set up for next state
      if (value <= 0)
      {
         lastDelayTime = time;
         fadeState = 3;
      }
   }
}

void delayFades()
{   
   // if delay time has passed set up amd go to next state (up)
   if (time - lastDelayTime > period)
   {
      lastFadeTime = time;
      fadeState = 0;
   }
}

void loop()
{
   time = millis();
   switch (fadeState)
   {
      case 0:
         fadeUp();
         break;
      case 1:
         fadeDown();
         break;
      case 3:
         delayFades();
         break;
   }
}

Please use code tags when posting code.