Arduino’s math library provides a wide range of functions to perform mathematical operations.
These functions can be used to solve complex problems, process sensor data, and create advanced algorithms.
This tutorial explains how to use the Arduino math library and demonstrates its functionality with examples.
Table of Contents
1. What Is the Math Library in Arduino?
The math library in Arduino is a collection of functions that help perform arithmetic, trigonometric, logarithmic, and rounding operations. These functions are part of the C standard library (math.h) and are included by default in Arduino.
2. Common Math Functions
2.1 Trigonometric Functions
- Used for angle-based calculations.
| Function | Description |
|---|---|
| sin(x) | Sine of angle x (radians). |
| cos(x) | Cosine of angle x (radians). |
| tan(x) | Tangent of angle x (radians). |
| asin(x) | Arc sine of x (returns radians). |
| acos(x) | Arc cosine of x (returns radians). |
| atan(x) | Arc tangent of x (returns radians). |
Example: Calculate Sine
void setup() {
Serial.begin(9600);
float angle = 1.0; // Angle in radians
float result = sin(angle);
Serial.print("Sine of angle: ");
Serial.println(result);
}
void loop() {
// Empty
}
2.2 Power and Exponentiation
| Function | Description |
|---|---|
| pow(base, exp) | Base raised to the power of exponent. |
| exp(x) | Exponential of x (e^x). |
| log(x) | Natural logarithm of x (base e). |
| log10(x) | Logarithm of x (base 10). |
Example: Calculate Power
void setup() {
Serial.begin(9600);
float base = 2.0;
float exponent = 3.0;
float result = pow(base, exponent);
Serial.print("2 raised to the power of 3 is: ");
Serial.println(result);
}
void loop() {
// Empty
}
2.3 Square Root and Absolute Value
| Function | Description |
|---|---|
| sqrt(x) | Square root of x. |
| abs(x) | Absolute value of x. |
Example: Calculate Square Root
void setup() {
Serial.begin(9600);
float number = 16.0;
float result = sqrt(number);
Serial.print("Square root of 16 is: ");
Serial.println(result);
}
void loop() {
// Empty
}
2.4 Rounding and Modulo
| Function | Description |
|---|---|
| ceil(x) | Rounds x up to the nearest integer. |
| floor(x) | Rounds x down to the nearest integer. |
| round(x) | Rounds x to the nearest integer. |
| fmod(x, y) | Returns the remainder of x divided by y. |
Example: Rounding and Modulo
void setup() {
Serial.begin(9600);
float number = 4.7;
Serial.print("Ceiling: ");
Serial.println(ceil(number));
Serial.print("Floor: ");
Serial.println(floor(number));
Serial.print("Rounded: ");
Serial.println(round(number));
Serial.print("Modulo (5.3 % 2): ");
Serial.println(fmod(5.3, 2));
}
void loop() {
// Empty
}
3. Practical Examples
3.1 Calculate Distance Using Pythagoras
void setup() {
Serial.begin(9600);
float x = 3.0;
float y = 4.0;
float distance = sqrt(pow(x, 2) + pow(y, 2)); // Pythagorean theorem
Serial.print("Distance: ");
Serial.println(distance);
}
void loop() {
// Empty
}
3.2 Normalize Sensor Data
Normalize a sensor value to a range of 0 to 1.
const int sensorPin = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(sensorPin);
float normalizedValue = sensorValue / 1023.0; // Normalize to range 0-1
Serial.print("Normalized Value: ");
Serial.println(normalizedValue);
delay(500);
}
3.3 Generate a Sine Wave for PWM Output
Create a smooth sine wave pattern for an LED using analogWrite().
const int ledPin = 9;
const float pi = 3.14159;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
for (int i = 0; i < 360; i++) {
float angle = i * (pi / 180); // Convert degrees to radians
float brightness = (sin(angle) + 1) * 127.5; // Map sine value to 0-255
analogWrite(ledPin, (int)brightness); // Output PWM signal
delay(10); // Delay for smooth transition
}
}
4. Best Practices for Using the Math Library
- Use Appropriate Data Types:
- Use float for functions like sin() or pow() to handle decimal precision.
- Convert Degrees to Radians:
- Trigonometric functions require angles in radians. Convert degrees using:
float radians = degrees * (PI / 180);
- Trigonometric functions require angles in radians. Convert degrees using:
- Avoid Integer Division:
- When working with integers, remember that division truncates decimals. Use float if precision is required.
- Optimize for Performance:
- Some functions like pow() can be computationally expensive. Simplify calculations where possible.
- Test Boundary Cases:
- Ensure that inputs to functions like sqrt() or log() are within valid ranges.
Conclusion
The Arduino math library provides powerful tools for performing a wide range of calculations, from simple arithmetic to complex trigonometry and logarithms.
Whether you’re normalizing sensor data, generating waveforms, or solving geometric problems, these functions can help simplify your code.
This tutorial covers the most commonly used math functions and demonstrates practical examples to help you integrate them into your Arduino projects.
For more details, visit the official Arduino reference.
