Language | Libraries | Comparison
Returns the remainder from an integer division
result = value1 % value2
value1: a byte, char, int, or long
value2: a byte, char, int, or long
The remainder from an integer division.
x = 7 % 5; // x now contains 2 x = 9 % 5; // x now contains 4 x = 5 % 5; // x now contains 0 x = 4 % 5; // x now contains 4
The modulo operator is useful for tasks such as making an event occur at regular periods or making a memory array roll over
// check a sensor every 10 times through a loop void loop(){ i++; if ((i % 10) == 0){ x = analogRead(sensPin); // read sensor every ten times through loop } / ... } // setup a buffer that averages the last five samples of a sensor int senVal[5]; // create an array for sensor data int i, j; // counter variables long average; // variable to store average ... void loop(){ // input sensor data into oldest memory slot sensVal[(i++) % 5] = analogRead(sensPin); average = 0; for (j=0; j<5; j++){ average += sensVal[j]; // add up the samples } average = average / 5; // divide by total
the modulo operator will not work on floats
Corrections, suggestions, and new documentation should be posted to the Forum.