Wrapping numbers around - BleepLabs/Arduino-Light-And-Sound GitHub Wiki

Wrapping numbers around

Sometimes we want a variable to get to a certain value and then reset to another fixed value. For example:
j++; //same as j=j+1
if (j>8){
  j=0;
}

-= (Minus Equal)

But what if we want j to increment by more than one?
If we just go back to 0 we'll loose the remainder. Sometimes that's waht needed but what if you want it to wrap around?

Lets say we want to continuously add values to the hue of a light. We can't go over 1.0 but we don't want to rest back to 0. One method would be subtracting the highest value, 1.0, each time we go over that value.

hue +=.3;
if (hue>1.0){
  hue -= 1.0; //hue = hue - 1.0
}

Here we've maintained the remainder. If we come in with 1.5 we get .5.
But what if we come in with 2.5?

While

Arduino reference
Any come in while will continue to happen as long as the condition is true.
If we come into this will 2.5 we'll get .5 out as it will execute the code in the curly brackets twice.

hue +=.3;
while (hue>1.0){
  hue -= 1.0; //hue = hue - 1.0
`}

You can think of it like a for loop that doesn't have a set end.
This means you can get code stuck in it indefinitely. while (1==1){ } has no escape and the code inside it will keep repeating, never continuing with the loop.

%

Arduino reference
Modulo aka reminder is similar to what we just did with while but only works on integers.
In this line of "class 4 - color arrays.ino" it's used to keep the variable we're using to select a value from an arry for going over 7 but also retain the remainder

hue_move = lfo[1] + x_count;
hue_move %= 8; //hue_move = hue_move % 8

remainder = dividend % divisor.
hue_move will never equal or go over 8. It'll just keep wrapping around
1%8=1, 7%8= 7, 8%8=0, 9%8=1, 17%8=1, 871498174%8= 6
You can use this calculator to try it out