How to increment until an upper limit value and then decrement back to zero?

I have 2 problems:

  1. I am trying to figure out a way to increase the speed of my motor from PWM 0 to 255, stepwise, and then decrement it back to zero, and repeat this forever. But i'm not sure what's the best approach?
  2. Also, when i use the variable pwm, it shows up in a different colour, so it seems to be a function within the Arduino IDE. But i couldn't find information on how to use it?

Here is my attempt:

float new_pwm=0; //global variable declaration

void loop() {
if (new_pwm < 255)
    new_pwm++;
else
    new_pwm--;
}

But i don't think the decrement part will work to change the PWM value back to zero, except to decrement the value only once from 255 to 254. I'm stuck. :confused:

byte new_pwm = 0;
. . .
if (new_pwm == 255)
{
value = -1;
}
if (new_pwm == 0)
{
value = 1;
}
new_pwm = new_pwm + value;

larryd:
byte new_pwm = 0;
. . .
if (new_pwm == 255)
{
value = -1;
}
if (new_pwm == 0)
{
value = 1;
}
new_pwm = new_pwm + value;

That worked. Thanks! :slight_smile:

But what about the pwm keyword in the Arduino IDE? I've been searching but i'm still puzzled on how to use it... Is there an example somewhere?

DryRun:
But what about the pwm keyword in the Arduino IDE? I've been searching but i'm still puzzled on how to use it... Is there an example somewhere?

Don't worry about the colouring. It does not always work and it has no effect on the program. I don't think the name PWM has any special significance,

what about the pwm keyword in the Arduino IDE?

Each library can have an associated file named keywords.txt that defines the colour of keywords used by the library.

This is meant to be useful but in practice is useless because the IDE checks for keywords in every installed library, as well as the system keywords, whether or not you are using the library in your current program

What is happening is that one of your installed libraries has an entry in its keywords.txt file defining the colour of the word pwm. Ignore it