Why is my looped code not repeating in the loop function?

This is a relatively simple program that I have to complete for a class, and I need to use a function to control the color of the led's to simulate a "traffic light." However, the function just isn't starting again. I have tried using return after the while loop, as well as setting a 4th case turn off all the lights, but nothing works.



void setup() {

pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);

}
void trafficLight (int color)  {
 
  switch (color) {
    
    case 1:
      digitalWrite(8,HIGH);
      digitalWrite(10,LOW);
      digitalWrite(9,LOW);
      break;
    case 2:
      digitalWrite(9,HIGH);
      digitalWrite(8,LOW);
      digitalWrite(10,LOW);
      break;
    case 3:
      digitalWrite(10,HIGH);
      digitalWrite(9,LOW);
      digitalWrite(8,LOW);
      break;
      case 4:
    digitalWrite(10,LOW);
    digitalWrite(9,LOW);
    digitalWrite(8,LOW);
    
                 }
    return;
  
}
void loop() {
  
 int times = millis();
int i=1;
      /*if (times < 2000) {
        trafficLight(1);
      }
      else if (2000 <= times <= 5000){
        trafficLight(2);
      }
      else if (times <= 10000) {
        trafficLight(3);
      }*/
      while (times <6500){
        trafficLight(i);
        i++;
        delay(2000);
      } 
      
    return;

}



This is because once the processor has been running for over six seconds this code never runs again.

1 Like

Try

      while ( millis()-times <6500){

P.S. and you must use unsigned long as the type for times

Non-blocking timing tutorials:
Blink without delay().
Beginner's guide to millis().
Several things at a time.

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