Math.ino 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* This file is part of the Razor AHRS Firmware */
  2. // Computes the dot product of two vectors
  3. float Vector_Dot_Product(const float v1[3], const float v2[3])
  4. {
  5. float result = 0;
  6. for(int c = 0; c < 3; c++)
  7. {
  8. result += v1[c] * v2[c];
  9. }
  10. return result;
  11. }
  12. // Computes the cross product of two vectors
  13. // out has to different from v1 and v2 (no in-place)!
  14. void Vector_Cross_Product(float out[3], const float v1[3], const float v2[3])
  15. {
  16. out[0] = (v1[1] * v2[2]) - (v1[2] * v2[1]);
  17. out[1] = (v1[2] * v2[0]) - (v1[0] * v2[2]);
  18. out[2] = (v1[0] * v2[1]) - (v1[1] * v2[0]);
  19. }
  20. // Multiply the vector by a scalar
  21. void Vector_Scale(float out[3], const float v[3], float scale)
  22. {
  23. for(int c = 0; c < 3; c++)
  24. {
  25. out[c] = v[c] * scale;
  26. }
  27. }
  28. // Adds two vectors
  29. void Vector_Add(float out[3], const float v1[3], const float v2[3])
  30. {
  31. for(int c = 0; c < 3; c++)
  32. {
  33. out[c] = v1[c] + v2[c];
  34. }
  35. }
  36. // Multiply two 3x3 matrices: out = a * b
  37. // out has to different from a and b (no in-place)!
  38. void Matrix_Multiply(const float a[3][3], const float b[3][3], float out[3][3])
  39. {
  40. for(int x = 0; x < 3; x++) // rows
  41. {
  42. for(int y = 0; y < 3; y++) // columns
  43. {
  44. out[x][y] = a[x][0] * b[0][y] + a[x][1] * b[1][y] + a[x][2] * b[2][y];
  45. }
  46. }
  47. }
  48. // Multiply 3x3 matrix with vector: out = a * b
  49. // out has to different from b (no in-place)!
  50. void Matrix_Vector_Multiply(const float a[3][3], const float b[3], float out[3])
  51. {
  52. for(int x = 0; x < 3; x++)
  53. {
  54. out[x] = a[x][0] * b[0] + a[x][1] * b[1] + a[x][2] * b[2];
  55. }
  56. }
  57. // Init rotation matrix using euler angles
  58. void init_rotation_matrix(float m[3][3], float yaw, float pitch, float roll)
  59. {
  60. float c1 = cos(roll);
  61. float s1 = sin(roll);
  62. float c2 = cos(pitch);
  63. float s2 = sin(pitch);
  64. float c3 = cos(yaw);
  65. float s3 = sin(yaw);
  66. // Euler angles, right-handed, intrinsic, XYZ convention
  67. // (which means: rotate around body axes Z, Y', X'')
  68. m[0][0] = c2 * c3;
  69. m[0][1] = c3 * s1 * s2 - c1 * s3;
  70. m[0][2] = s1 * s3 + c1 * c3 * s2;
  71. m[1][0] = c2 * s3;
  72. m[1][1] = c1 * c3 + s1 * s2 * s3;
  73. m[1][2] = c1 * s2 * s3 - c3 * s1;
  74. m[2][0] = -s2;
  75. m[2][1] = c2 * s1;
  76. m[2][2] = c1 * c2;
  77. }