Go Down

Topic: Why does the order of this code change if an LED blinks or not? (Read 903 times) previous topic - next topic

SheCurvesMobius

Why is it that when I write my code this way in the "FOR LOOP A", pin 10 blinks during "FOR LOOP A":


Code: [Select]
int timer = 100;

void setup() {
  // Initialize each pin as an output
  for (int thisPin = 2; thisPin < 8; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
  pinMode(10, OUTPUT);
}

void loop() {
  // "FOR LOOP A"
  // loop from the lowest pin to the highest:
  for (int thisPin = 2; thisPin < 8; thisPin++) {
    digitalWrite(thisPin, HIGH);
    delay(timer);
    digitalWrite(thisPin, LOW);

    digitalWrite(10, HIGH);
    delay(timer);
    digitalWrite(10, LOW);
   }
 
  // "FOR LOOP B"
  // loop from the highest pin to the lowest:
  for (int thisPin = 7; thisPin >= 2; thisPin--) {
    digitalWrite(thisPin, HIGH);
    delay(timer);
    digitalWrite(thisPin, LOW);
   
  }
}


But if I write it this way in the "FOR LOOP A", it stays on for all of "FOR LOOP A" and then turns off right before "FOR LOOP B" starts? I can't understand the logic. I feel like it should blink durring "FOR LOOP A".



Code: [Select]
int timer = 100;

void setup() {
  // Initialize each pin as an output
  for (int thisPin = 2; thisPin < 8; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
  pinMode(10, OUTPUT);
}

void loop() {
  // "FOR LOOP A"
  // loop from the lowest pin to the highest:
  for (int thisPin = 2; thisPin < 8; thisPin++) {
    digitalWrite(thisPin, HIGH);
    digitalWrite(10, HIGH);
    delay(timer);
    digitalWrite(thisPin, LOW);
    digitalWrite(10, LOW);
   }
 
  // "FOR LOOP B"
  // loop from the highest pin to the lowest:
  for (int thisPin = 7; thisPin >= 2; thisPin--) {
    digitalWrite(thisPin, HIGH);
    delay(timer);
    digitalWrite(thisPin, LOW);
   
  }
}



Thanks for your help!

dlloyd

In your second example, the output only appears to be always on, but it impulses low just for the time it takes to start the next iteration then write it high again. You'll need to delay after each transition so the high and low time remains equal.

Code: [Select]
int timer = 100;

void setup() {
  // Initialize each pin as an output
  for (int thisPin = 2; thisPin < 8; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
  pinMode(10, OUTPUT);
}

void loop() {
  // "FOR LOOP A"
  // loop from the lowest pin to the highest:
  for (int thisPin = 2; thisPin < 8; thisPin++) {
    digitalWrite(thisPin, HIGH);
    digitalWrite(10, HIGH);
    delay(timer);
    digitalWrite(thisPin, LOW);
    digitalWrite(10, LOW);
    delay(timer);
  }

  // "FOR LOOP B"
  // loop from the highest pin to the lowest:
  for (int thisPin = 7; thisPin >= 2; thisPin--) {
    digitalWrite(thisPin, HIGH);
    delay(timer);
    digitalWrite(thisPin, LOW);
    delay(timer);
  }
}

SheCurvesMobius

Ah, of course!! Thank you so much. That helps me a great deal!

Go Up