Fade sketch from basic examples. Which is the best sintax in the if statement?

Hello. I was testing the basic examples from the IDE.
I found that code of the sketch from basic examples, has something weird for me in the IF statement.

void loop() {
 // set the brightness of pin 9:
 analogWrite(led, brightness);

 // change the brightness for next time through the loop:
 brightness = brightness + fadeAmount;

 // reverse the direction of the fading at the ends of the fade:
 if (brightness <= 0 || brightness >= 255) {
   fadeAmount = -fadeAmount;
 }
Serial.println(fadeAmount);  
Serial.println(brightness); 
 // wait for 30 milliseconds to see the dimming effect
 delay(30);

I think the line
if (brightness <= 0 || brightness >= 255)
should be;
if (brightness == 0 || brightness == 255)
In the first case, brightnes is never going to be under 0 or over 255.
Why using "<= , >=" then ?
it works exactly the same as the second case, that I think is the correct one.
I tested both and read the serial. The output is the same.

Adding the fade amount could cause brightness to be outside of 0-255.

Example brightness = 250
fadeAmount = 10

brightness + fadeAmount = 260.

By using <= and >= you catch these cases.

1 Like

What type is brightness

<= will work, many times it is preferably as a guard against going negative when the variable is an integer.

=> is often preferable too.

That is only true as long as the range is evenly divided by the 'fadeAmount'. If 'fademount' is some value greater than 1 you may go below 0 or above 255.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.