Blinking two LEDs in and out of phase

Thank you very much!
why you set the " whichPattern" inside the: default: done = true; // No such pattern whichPattern = -1; // before the first pattern
to be -1? why not 0?

Iv'e added option to also determine the onTime of led2 independently from led1:

/ Return 'true' when done.
boolean blink(unsigned long onTime,unsigned long onTime2, unsigned long phaseDifference, unsigned long rate, unsigned long repetitions)
{
  if (cycleCount >= repetitions)
    return true; // done

  unsigned long timePassed = millis() - previousMillis;

  if (timePassed >= rate)
  {
    previousMillis = millis(); // Start a new cycle
    timePassed = 0;
    cycleCount++;
  }

  if (timePassed < onTime)
  {
    digitalWrite(led1, HIGH);
  }
  else
  {
    digitalWrite(led1, LOW);
  }

  if (timePassed >= phaseDifference && timePassed < (phaseDifference + onTime2))
    digitalWrite(led2, HIGH);
  else
    digitalWrite(led2, LOW);

  return false; // Not done yet
}

is it possible to add an option that if no number is added to the place of 'onTime2' at the function void blink() it will be initialised to the value of onTime ?

because:

  if (done)
    whichPattern++; // next pattern

at the first time when void loop() { static int whichPattern = 0; boolean done = false; is starting to run which pattern is equal to 0 and done = false
then, -

switch (whichPattern)
  {
    case 0:
      done = blink(50, 0, 500, 10);
      break;

case 0 is always will be the first because we initial at the top of the loop() function the 'whichPattern' to be 0.

at what case the default of the switch case is happening ?

Read up on the 'static' keyword.

If I got it correctly - the static keyword is available only for that particular function (in our case the void loop(){} function , but in difference from local variable it is not destroyed each time it been called inside other functions(?)

I still can't see a case when the default statement is happening (true)

The 'default' case is used if no matching case is found. Like when 'case 1:' is done and

  if (done)
    whichPattern++; // next pattern

sets 'whichPattern' to 2. There is no match for 2 so the default case is used.

I see! so when case 1 is done the if(done) is true and whichPattern++ is execute - therefore whichPattern is now equal 2. because there is no pattern 2 the default statement in the switch function is happening.
At the default - done is set to be true and whichPattern set to be -1 . then we get into the if(done) statement. Because done is set to be true we indeed go inside that if statement and whichpattern++; turn 'whichPattern' that is equal to -1, to be equal 0 and we again iterate over the switch function...

My English is full of mistakes but I think I got it.
Thanks!

I think you do. Your English is understandable and your explanation is correct.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.