我正在此 Nextion 显示屏上编写界面。具体来说,我正在尝试编写一个围绕中心点旋转的数字表盘。
这些屏幕很棒,但它们没有任何三角函数,没有浮点,也不能旋转图像。只是分享这些规格作为我的限制背景,不用担心屏幕。
我需要一种将 X,Y 坐标转换为 0-359 输出的方法。
有人知道使用整数数学来近似角度的任何技巧或窍门吗?
我现在所拥有的只是针对每个四分位数调整的梯度,但它不是线性的,因为我只是在做上升/运行。
有一篇论文反正切函数的高效近似描述了快速
atan
函数:
double FastArcTan(double x)
{
return M_PI_4*x - x*(fabs(x) - 1)*(0.2447 + 0.0663*fabs(x));
}
这当然使用
double
数据类型。
重写为比例因子为10000的整数算术(因此“(int) 10000”实际上意味着“1.0”)你可以编写一个函数
int IntArcTan(int x_scaled)
,这里是完整的小测试程序:
#include <stdio.h>
#include <math.h>
// -10000 < x_scaled < 10000; integer arithmetic i.e. (int)10000 means (float)1.0000
int IntArcTan(int x_scaled)
{
int abs_x_scaled = x_scaled >= 0 ? x_scaled : -x_scaled;
int a = 7854/* PI/4 */ * x_scaled / 10000;
int b = x_scaled*(abs_x_scaled - 10000) / 10000;
int c = b * 2447 / 10000;
int d = b * 663 / 10000 * abs_x_scaled / 10000;
return a - c - d;
}
int main()
{
for (double x = -1.; x < 1.; x+=.01)
{
double atan_std = atan(x);
int atan_int_scaled = IntArcTan((int)(x * 10000));
double atan_int = (double)atan_int_scaled / 10000;
printf("x = %10.3f, atan_std(x) = %10.3f, atan_int(x) = %10.3f, error = %10.3f%%\n", x, atan_std, atan_int, atan_int/atan_std*100-100);
}
}
您只需要记住缩放整数算术变量(1.0 -> 10000),并且
atan
的最终输出以弧度为单位,以便获得度数 atan_int_scaled * 90 / 7854