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 Answer 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;
}
}
}
answered Jun 20, 2020 at 21:08
-
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– jsotola2020年06月20日 22:17:40 +00:00Commented Jun 20, 2020 at 22:17 -
1Wouldn'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– Duncan C2020年07月20日 22:52:29 +00:00Commented Jul 20, 2020 at 22:52
i
andj
, in the twofor
loops ... they can both bei
.... increment can be done usingi++
instead ofi+=1
... same with decrement