Fade Basic Examples

There is an error in the example code:
The if should check for brightness < 255 and not <=255.

No.

There is a potential problem with the code if the value of fadeAmount is changed but not the one pointed out erroneously by the OP.

The value of the fadeAmount is changed to 6; the PWM effect on the LED is still there, and it is very similar to the one with fadeAmount = 5 except that there is a sudden break kick on the LED which could be the 'potential problem' as pointed in Post#2.

GolamMostafa:
The value of the fadeAmount is changed to 6; the PWM effect on the LED is still there, and it is very similar to the one with fadeAmount = 5 except that there is a sudden break which could be the 'potential problem' as pointed in Post#2.

That's what I had in mind

@UKHeliBob

You intuition has turned to be right. The discovery has created a new job for us to do critical analysis on the given program codes to find the reason (s) why the program behaves well with 5 and 255; 3 and 210; 6 and 240; 7 and 210; ....; and not for 6 and 255.

A new job?
Or simple arithmetic?

It depends on experience/expertise level.

At a first glance, someone might observe: 255 = 5x51; 210 = 3x70; 240 = 6x40; 210 = 7x30. But, the program also works well (no kick) with 8 and 210, where 210 is not a multiple of 8!

Why?
Let's say brightness(b) is 260, then fade(f) will be -5 because 260>255. Then b will be 255 and f will be +5. But f should remain -5 to decrease b until 0.

@tik1

Please, look at the syntax of analogWrite() function as extracted from Arduino Reference Manual.

Syntax
analogWrite(pin, value)

Parameters
pin: the pin to write to. Allowed data types: int.
value: the duty cycle: between 0 (always off) and 255 (always on). Allowed data types: int

How can you assume a value of 260 for the variable brightness?

My fault, please close the thread. Sorry for your time token!

How would brightness ever get to 260?

Because in the example the range check and correction of fadeAmount happens after the analogWrite()

The example code with comments removed for brevity

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by

void setup()
{
  pinMode(led, OUTPUT);
}

void loop()
{
  analogWrite(led, brightness);
  brightness = brightness + fadeAmount;
  if (brightness <= 0 || brightness >= 255)
  {
    fadeAmount = -fadeAmount;
  }
  delay(30);
}

All OK when fadeAmount is 5 but when it is say 6 think what happens to the value of brightness.