C Attitude Math Library
Quaternion, Euler, and DCM math utilities for attitude control.
Loading...
Searching...
No Matches
euler.c
Go to the documentation of this file.
1#include "attitude/euler.h"
2#include <math.h>
3#include <stddef.h>
4
5static void set_nan_matrix(double dcm[3][3]) {
6 if (dcm == NULL) {
7 return;
8 }
9 for (int row = 0; row < 3; ++row) {
10 for (int column = 0; column < 3; ++column) {
11 dcm[row][column] = NAN;
12 }
13 }
14}
15
16int euler_to_dcm_checked(const EulerAngles *e, double dcm[3][3]) {
17 if (e == NULL || dcm == NULL || e->order != EULER_ZYX ||
18 !isfinite(e->roll) || !isfinite(e->pitch) || !isfinite(e->yaw)) {
19 return 0;
20 }
21
22 double cr = cos(e->roll);
23 double sr = sin(e->roll);
24 double cp = cos(e->pitch);
25 double sp = sin(e->pitch);
26 double cy = cos(e->yaw);
27 double sy = sin(e->yaw);
28
29 dcm[0][0] = cy*cp;
30 dcm[0][1] = cy*sp*sr - sy*cr;
31 dcm[0][2] = cy*sp*cr + sy*sr;
32 dcm[1][0] = sy*cp;
33 dcm[1][1] = sy*sp*sr + cy*cr;
34 dcm[1][2] = sy*sp*cr - cy*sr;
35 dcm[2][0] = -sp;
36 dcm[2][1] = cp*sr;
37 dcm[2][2] = cp*cr;
38 return 1;
39}
40
41void euler_to_dcm(const EulerAngles *e, double dcm[3][3]) {
42 if (!euler_to_dcm_checked(e, dcm)) {
43 set_nan_matrix(dcm);
44 }
45}
46
47int euler_to_quaternion_checked(const EulerAngles *e, double q[4]) {
48 if (e == NULL || q == NULL || e->order != EULER_ZYX ||
49 !isfinite(e->roll) || !isfinite(e->pitch) || !isfinite(e->yaw)) {
50 return 0;
51 }
52
53 double cr = cos(e->roll/2.0);
54 double sr = sin(e->roll/2.0);
55 double cp = cos(e->pitch/2.0);
56 double sp = sin(e->pitch/2.0);
57 double cy = cos(e->yaw/2.0);
58 double sy = sin(e->yaw/2.0);
59
60 q[0] = cr*cp*cy + sr*sp*sy; // w
61 q[1] = sr*cp*cy - cr*sp*sy; // x
62 q[2] = cr*sp*cy + sr*cp*sy; // y
63 q[3] = cr*cp*sy - sr*sp*cy; // z
64 return 1;
65}
66
67void euler_to_quaternion(const EulerAngles *e, double q[4]) {
68 if (!euler_to_quaternion_checked(e, q) && q != NULL) {
69 for (int index = 0; index < 4; ++index) {
70 q[index] = NAN;
71 }
72 }
73}
int euler_to_quaternion_checked(const EulerAngles *e, double q[4])
Checked Euler-to-quaternion conversion.
Definition euler.c:47
void euler_to_dcm(const EulerAngles *e, double dcm[3][3])
Convert Euler angles to a direction cosine matrix.
Definition euler.c:41
void euler_to_quaternion(const EulerAngles *e, double q[4])
Convert Euler angles to a quaternion.
Definition euler.c:67
int euler_to_dcm_checked(const EulerAngles *e, double dcm[3][3])
Checked Euler-to-DCM conversion.
Definition euler.c:16
@ EULER_ZYX
Standard aerospace yaw → pitch → roll sequence.
Definition euler.h:15
Storage for Euler angles with an associated rotation order.
Definition euler.h:26
double pitch
Rotation about y-axis.
Definition euler.h:28
double yaw
Rotation about z-axis.
Definition euler.h:29
EulerOrder order
Intrinsic rotation order.
Definition euler.h:30
double roll
Rotation about x-axis.
Definition euler.h:27