atan2()
[Math]
double atan2(double y, double x);Description
Returns the principal value of the arc tangent of $\frac{y}{x}$ in radians, using the signs of both arguments to determine the quadrant of the return value.
Parameters
x: The x-coordinate of the point.
y: The y-coordinate of the point.
Returns
The principal value of the arc tangent of $\frac{y}{x}$ in radians.
Example Code
The code reads the values of two potentiometer connected to pins
INY and INX and place the tangent to the pin
OUT.
void setup() {
pinLabel(0, "INY"); // set the label of pin 0 to "INY"
pinLabel(1, "INX"); // set the label of pin 1 to "INX"
pinLabel(2, "OUT"); // set the label of pin 2 to "OUT"
pinMode(2, OUTPUT); // set pin 2 as output
pinLabel(3, "VCC"); // set the label of pin 3 to "VCC"
powerPin(3); // set pin 3 as power pin
pinLabel(4, "GND"); // set the label of pin 4 to "GND"
groundPin(4); // set pin 4 as ground pin
}
void loop() {
// read the value of the potentiometers
int val_x = analogRead(0);
int val_y = analogRead(1);
// map the values to the range of 0 to 180
double angle_y = map(val_x, 0, 1023, 0, 180);
double angle_x = map(val_y, 0, 1023, 0, 180);
// calculate the arc tangent of the angle in radians
double atan2Val = atan2(angle_x * PI / 180, angle_y * PI / 180);
// map the value to the range of 0 to 1023
analogWrite(2, (int) atan2Val * 1023);
// delay for 100ms
delay(100);
}Notes and Warnings
- The angle should be in radians. To convert the angle from degrees to
radians, multiply the angle by
PI / 180. - The output value is in the range of −π to π.
