MATH FUNCTIONS
Arduino includes many common mathematical and trigonometric functions:
min(x, y)
Returns the smaller of x and y.
Example:
val = min(10,20); // val is now 10
max(x, y)
Returns the larger of x and y.
Example:
val = max(10,20); // val is now 20
abs(x)
Returns the absolute value of x, which turns negative numbers into positive. If x is 5 it will return 5, but if x is –5, it will still return 5.
Example:
val = abs(-5); // val is now 5
constrain(x, a, b)
Returns the value of x, constrained between a and b. If x is less than a, it will just return a and if x is greater than b, it will just return b.
Example:
val = constrain(analogRead(0), 0, 255); // reject values bigger than 255
map(value, fromLow, fromHigh, toLow, toHigh)
Maps a value in the range fromLow and maxLow to the range toLow and toHigh. Very useful to process values from analogue sensors.
Example:
val = map(analogRead(0),0,1023,100, 200); // maps the value of
// analog 0 to a value
// between 100 and 200double pow(base, exponent)
Returns the result of raising a number (base) to a value (exponent).
Example:
double x = pow(y, 32); // sets x to y raised to the 32nd power
double sqrt(x)
Returns the square root of a number.
Example:
double a = sqrt(1138); // approximately 33.73425674438
double sin(rad)
Returns the sine of an angle specified in radians.
Example:
double sine = sin(2); // approximately 0.90929737091
double cos(rad)
Returns the cosine of an angle specified in radians.
Example:
double cosine = cos(2); // approximately -0.41614685058
double ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access