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.

  • 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 – jsotola Jun 20 at 22:21
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;
  }
  }

}

| improve this answer | |
  • 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--) { – jsotola Jun 20 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. – Duncan C Jul 20 at 22:52

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.