Variable does not bounce back as desired (LED's)
If \$x\$ is a byte variable (uint8_t, for example), then it makes sense that your code doesn't work. Also, your code presumes a signed value. That may be another problem. However, C compilers can violate rules, too. Try something like this:

if ( x &gt; (255 - rate) ) {
    rate= -rate; /* not sure why you want to do that */
    x= 255;
} else
    x += rate;


Similar logic would apply in the negative direction, I think.

This allows you to keep it as a byte variable, though you need to think closely here. If x is a byte variable and it is signed, then even the code above won't work right. The maximum value is 127, then. Not 255.

Let's suppose you want x as a uint8_t. And you want this to go up and then down and then up and then down, etc. You now have another problem. That is that rate itself needs to be signed. So let's assume the following definitions:

uint8_t x;    /* unsigned from 0 to 255 */
int8_t rate;  /* signed from -128 to 127 */


Then try something like this:

if ( rate &gt; 0 &amp;&amp; x &gt; (255 - (uint8_t) rate) ) {
    rate= -rate;
    x= 255;
} else if ( rate &lt; 0 &amp;&amp; x &lt; (uint8_t) (-rate) ) {
    rate= -rate;
    x= 0;
} else
    x += rate;


Rate will then flip directions here, appropriately, and this allows you to keep the variables with small sizes, too.