Reference   Language (extended) | Libraries | Comparison | Board

% (modulo)

Description

Returns the remainder from an integer division

Syntax

result = value1 % value2

Parameters

value1: a byte, char, int, or long

value2: a byte, char, int, or long

Returns

The remainder from an integer division.

Examples

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

Example Code

// check a sensor every 10 times through a loop
void loop(){
i++;
if ((i % 10) == 0){          // read sensor every ten times through loop
   x = analogRead(sensPin);   
   }
/ ...
}

// 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 can also be used to strip off the high bits of a variable. The example below is from the Firmata library.

    // send the analog input information (0 - 1023)
     Serial.print(value % 128, BYTE); // send lowest 7 bits  
     Serial.print(value >> 7, BYTE);  // send highest three bits  

Tip

the modulo operator will not work on floats

See also

division

Reference Home

Corrections, suggestions, and new documentation should be posted to the Forum.

The text of the Arduino reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.