@@ -44,6 +44,33 @@ __attribute__((weak)) void _sincos(float a, float* s, float* c){
4444 *c = _cos (a);
4545}
4646
47+ // fast_atan2 based on https://math.stackexchange.com/a/1105038/81278
48+ // Via Odrive project
49+ // https://github.com/odriverobotics/ODrive/blob/master/Firmware/MotorControl/utils.cpp
50+ // This function is MIT licenced, copyright Oskar Weigl/Odrive Robotics
51+ // The origin for Odrive atan2 is public domain. Thanks to Odrive for making
52+ // it easy to borrow.
53+ __attribute__ ((weak)) float _atan2(float y, float x) {
54+ // a := min (|x|, |y|) / max (|x|, |y|)
55+ float abs_y = fabsf (y);
56+ float abs_x = fabsf (x);
57+ // inject FLT_MIN in denominator to avoid division by zero
58+ float a = min (abs_x, abs_y) / (max (abs_x, abs_y));
59+ // s := a * a
60+ float s = a * a;
61+ // r := ((-0.0464964749 * s + 0.15931422) * s - 0.327622764) * s * a + a
62+ float r =
63+ ((-0 .0464964749f * s + 0 .15931422f ) * s - 0 .327622764f ) * s * a + a;
64+ // if |y| > |x| then r := 1.57079637 - r
65+ if (abs_y > abs_x) r = 1 .57079637f - r;
66+ // if x < 0 then r := 3.14159274 - r
67+ if (x < 0 .0f ) r = 3 .14159274f - r;
68+ // if y < 0 then r := -r
69+ if (y < 0 .0f ) r = -r;
70+
71+ return r;
72+ }
73+
4774
4875// normalizing radian angle to [0,2PI]
4976__attribute__ ((weak)) float _normalizeAngle(float angle){
@@ -60,14 +87,10 @@ float _electricalAngle(float shaft_angle, int pole_pairs) {
6087// https://reprap.org/forum/read.php?147,219210
6188// https://en.wikipedia.org/wiki/Fast_inverse_square_root
6289__attribute__ ((weak)) float _sqrtApprox(float number) {// low in fat
63- // float x;
64- // const float f = 1.5F; // better precision
65-
66- // x = number * 0.5F;
67- float y = number;
68- long i = * ( long * ) &y;
69- i = 0x5f375a86 - ( i >> 1 );
70- y = * ( float * ) &i;
71- // y = y * ( f - ( x * y * y ) ); // better precision
72- return number * y;
90+ union {
91+ float f;
92+ uint32_t i;
93+ } y = { .f = number };
94+ y.i = 0x5f375a86 - ( y.i >> 1 );
95+ return number * y.f ;
7396}
0 commit comments