void loop() {
for (int i = 0; i < 255; i++){ //if i is less than 255 then increase i with 1
analogWrite(LED, i); //write the i value to pin 11
delay(5); //wait 5 ms then do the for loop again
}
for (int i = 255; i > 0; i--){ //descrease i with 1
analogWrite(LED, i);
delay(5);
}
}
Why do you want to do this? Are you trying to implement a state machine for this.
If so make your loop index i a static int variable set to zero. Next line do the analogWrite, then increment i and check that it is less than 255. If it is then set the return time to the delay value and exit the function. Do not renter the function until that time has passed.
There might be some other stuff that the sketch needs to do
... then the requirement should be formulated: write non-blocking code to enable the sketch do something else in parallel. But asking for B but targeting A is strange.
because they want to implement a state machine
The same story. Then the requirement should be "write a state machine"
@PaulRB: simpler in code for shure, but I don't think that this is easier to understand for the TO.
Was there any particular reason why you have chosen a static int16_t direction instead of an 8 bit integer?
To me, its easier to understand. For example direction=true or false does not, by itself, tell you what should happen to "i". Incrementing is no more "true" than decrementing from a common sense point of view. But direction=1 or -1 is more indicative.
I chose int16_t to match the definition of "i". They could both be int8_t. This would be slightly more efficient on AVR based Arduino. But on SAMD21 or ESP8266 based Arduino for example, it would make no difference.