1

My goal in pseudo code is :

only LED-6 HIGH for 6 seconds, then only LED-7 HIGH for 2 seconds, then only LED-8 HIGH for 4 seconds, then restart

This is very easy with delay(), but I struggle with millis(). Here is my code. Only led 7 and 8 blinks.

unsigned long currentTime;
unsigned long previousTime1 = 0;
unsigned long previousTime2 = 0;
unsigned long previousTime3 = 0;
unsigned long interval1 = 6000;
unsigned long interval2 = 2000;
unsigned long interval3 = 4000;

void setup() {

  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);


}

void loop() {

  currentTime = millis();

  if (currentTime - previousTime1 >= interval1){
    previousTime1 = currentTime;
    digitalWrite(6, HIGH);
    digitalWrite(7, LOW);
    digitalWrite(8, LOW);
  }

  if (currentTime - previousTime2 >= interval2){
    previousTime2 = currentTime;
    digitalWrite(6, LOW);
    digitalWrite(7, HIGH);
    digitalWrite(8, LOW);
  }

   if (currentTime - previousTime3 >= interval3){
    previousTime3 = currentTime;
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    digitalWrite(8, HIGH);
  }
}
1

A way to make this work is to use only one previousTime variable, rather than three of them.

When the program as shown above starts out, millis() is in fact close to 0, so none of the three LEDs should light up in the first 2 seconds. At the 2 second mark, LED 7 comes on. previousTime2 gets set to current time, so the second if is not going to be satisfied for 2 more seconds. At that point, LED 7 and 8 are in a race to see which one turns on second; whichever turns on first at the 4-second mark gets turned off within milliseconds, because when any LED turns on, the code turns off the other two LEDs. Whenever the condition for LED 6 is met, so is the condition for at least one of 7 or 8; so 6 can't stay on more than 2 seconds at most, and even then is in a race with 7 and 8 to come in third.

With a single previousTime variable, code like the following might work.

current = (millis() - previousTime)/1000;
if (current < 6) {
  digitalWrite(6, HIGH); // turn on 6
} else {
  digitalWrite(6, LOW);  // turn off 6
}
if (current >= 6 && current < 8) {
  digitalWrite(7, HIGH); // turn on 7
} else {
  digitalWrite(7, LOW);  // turn off 7
}
if (current >= 8) {
  digitalWrite(8, HIGH); // turn on 8
} else {
  digitalWrite(8, LOW);  // turn off 8
}
if (current >= 12) {
  previousTime = millis();
}

Note, the following code has the same effect.

current = (millis() - previousTime)/1000;
digitalWrite(6, current < 6);                 // turn 6 on or off
digitalWrite(7, current >= 6 && current < 8); // turn 7 on or off
digitalWrite(8, current >= 8);                // turn 8 on or off
if (current >= 12) {
  previousTime = millis();
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.