由于单片机解三角函数、反三角函数耗时太大,故此常常使用查表法来解。查表法所用数据可以通过Matlab事先计算所得,放置程序。注意,要求精度越高,放置数据量所占空间越大,故此需要权衡。
一、边角关系
(正弦) Sinθ = 对边A / 斜边C
(余弦) Cosθ = 邻边B / 斜边C
(正切) Tanθ = 对边A / 邻边B
二、弧度与角转换
#define pi 3.141592653f
float ToRad(float degree)
{
return (degree*pi/180.0);
}
三、查表法
SIN_TAB[90]=
{
0.8415 0.9093 0.1411 -0.7568 -0.9589 -0.2794 0.6570 0.9894 0.4121 -0.5440
-1.0000 -0.5366 0.4202 0.9906 0.6503 -0.2879 -0.9614 -0.7510 0.1499 0.9129
0.8367 -0.0089 -0.8462 -0.9056 -0.1324 0.7626 0.9564 0.2709 -0.6636 -0.9880
-0.4040 0.5514 0.9999 0.5291 -0.4282 -0.9918 -0.6435 0.2964 0.9638 0.7451
-0.1586 -0.9165 -0.8318 0.0177 0.8509 0.9018 0.1236 -0.7683 -0.9538 -0.2624
0.6702 0.9866 0.3959 -0.5588 -0.9998 -0.5216 0.4362 0.9929 0.6367 -0.3048
-0.9661 -0.7392 0.1674 0.9200 0.8268 -0.0266 -0.8555 -0.8979 -0.1148 0.7739
0.9511 0.2538 -0.6768 -0.9851 -0.3878 0.5661 0.9995 0.5140 -0.4441 -0.9939
-0.6299 0.3132 0.9684 0.7332 -0.1761 -0.9235 -0.8218 0.0354 0.8601 0.8940
}
调用
#define DSIN(x) (SIN_TAB[x]) /*不会大于90°*/
四、OpenCV:fastAtan2函数
static const float atan2_p1 = 0.9997878412794807f*(float)(180/CV_PI);
static const float atan2_p3 = -0.3258083974640975f*(float)(180/CV_PI);
static const float atan2_p5 = 0.1555786518463281f*(float)(180/CV_PI);
static const float atan2_p7 = -0.04432655554792128f*(float)(180/CV_PI);
float fastAtan2( float y, float x )
{
float ax = std::abs(x), ay = std::abs(y);//首先不分象限,求得一个锐角角度
float a, c, c2;
if( ax >= ay )
{
c = ay/(ax + (float)DBL_EPSILON);
c2 = c*c;
a = (((atan2_p7*c2 + atan2_p5)*c2 + atan2_p3)*c2 + atan2_p1)*c;
}
else
{
c = ax/(ay + (float)DBL_EPSILON);
c2 = c*c;
a = 90.f - (((atan2_p7*c2 + atan2_p5)*c2 + atan2_p3)*c2 + atan2_p1)*c;
}
if( x < 0 )//锐角求出后,根据x和y的正负性确定向量的方向,即角度。
a = 180.f - a;
if( y < 0 )
a = 360.f - a;
return a;
}
参考:https://blog.csdn.net/honpey/article/details/8957275