1

I would like to exit a particular loop if the state of an input changes from LOW to HIGH. This is the current loop:

void brakeFade() {
pixels.clear();
pixels.setBrightness(255);
pixels.fill(16711680, 0, 0);

for(int i=255; i>=10; i-=1) {
  pixels.setBrightness(i);
  pixels.show();
  delay(5);
  }
for(int j=10; j<=255; j+=1) {
  pixels.setBrightness(j);
  pixels.show();
  delay(5);

} }

I need that loop to exit if

(digitalRead(brakeFeed) == LOW)

Changes to HIGH during the loop.

1
  • there is no reason to use two different named index variables, i and j, in the two for loops ... they can both be i .... increment can be done using i++ instead of i+=1 ... same with decrement Commented Jun 20, 2020 at 22:21

1 Answer 1

1

figured it out:

void brakeFade2() {
pixels.clear();
pixels.setBrightness(255);
pixels.fill(16711680, 0, 0);

for(int i=255; i>=10; i-=1) {
  if (digitalRead(brakeFeed) == LOW){
  pixels.setBrightness(i);
  pixels.show();
  delay(5);
  }
  else {
    break;
  }
}
for(int j=10; j<=255; j+=1) {
  if (digitalRead(brakeFeed) == LOW){
  pixels.setBrightness(j);
  pixels.show();
  delay(5);
  }
  else {
    break;
  }
  }

}

2
  • simpler way would be to add it to the completion test of the for loop ... for(int i=255; (i>=10) or (digitalRead(brakeFeed) == LOW); i--) { Commented Jun 20, 2020 at 22:17
  • 1
    Wouldn't that be for(int i=255; (i>=10) && (digitalRead(brakeFeed) == LOW)? The OP wants the loop to continue as long as is >= 10, and the brakeFeed pin still reads as low. It should break if either of those stops being the case. Commented Jul 20, 2020 at 22:52

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.