参考博文:计算的公式推导
根据博文的公式,得出算法,未经实际验证,记录一下,待验证之后,如有不妥会更新。仅供参考。
#include <math.h>
typedef struct
{
float X_arctan;
float Y_arctan;
float Z_arctan;
float X_angle;
float Y_angle;
float Z_angle;
} G_sensor_t;
#define PI 3.1415926
/*********************************************
* @brief 获取重力加速度分量数据
* @param min_dpi:数据分辨率最小值(1g)
* @param max_dpi:数据分辨率最大值(1g)
* @param now_val:对应轴传感器值,实际读取寄存器的值
* @retval 返回重力加速度的分量值
* @note 数据分辨率的计算方式:以2g分辨率为例,陀螺仪adc是12位分辨率。
* 正负2g的分辨率,一起是4g的分辨率,也就是把4096分成4分,即,1g的数据AD范围:正:0~1024
* 负:-1024~0。因此,数据最大值是1024,最小值是-1024
********************************************/
float get_GravitationalAcceleration(int16_t min_dpi, int16_t max_dpi, int16_t now_val)
{
float temp;
if (now_val > max_dpi)
{
now_val = max_dpi;
}
if (now_val < min_dpi)
{
now_val = min_dpi;
}
temp = (float)((max_dpi - min_dpi) >> 1); //计算数据分辨率,((max_dpi - min_dpi) >> 1) => (max_dpi - min_dpi)/2.0
temp = 9.8 / temp; //计算1个AD值代表的g值,g = 9.8
temp = now_val * temp; //计算当前AD值代表的g值
return temp;
}
/*********************************************
* @brief 获取重力加速度芯片相对水平位置的夹角
* @param *sensor:相关的参数变量,计算得出的反正弦值和角度数据
* @param x_val:X轴传感器的值
* @param y_val:Y轴传感器的值
* @param z_val:Z轴传感器的值
* @retval NULL
* @note 实际使用,调用该函数即可
********************************************/
void get_angle_value(G_sensor_t *sensor, int16_t x_val, int16_t y_val, int16_t z_val)
{
float Ax, Ay, Az, temp;
Ax = get_GravitationalAcceleration(-1024, 1024, x_val);
Ay = get_GravitationalAcceleration(-1024, 1024, y_val);
Az = get_GravitationalAcceleration(-1024, 1024, z_val);
temp = sqrt((Ay * Ay) + (Az * Az));
sensor->X_arctan = atan(Ax / temp);
temp = sqrt((Ax * Ax) + (Az * Az));
sensor->Y_arctan = atan(Ay / temp);
temp = sqrt((Ax * Ax) + (Ay * Ay));
sensor->Z_arctan = atan(Az / temp);
temp = 180.0 / PI;
sensor->X_angle = sensor->X_arctan * temp;
sensor->Y_angle = sensor->Y_arctan * temp;
sensor->Z_angle = sensor->Z_arctan * temp;
}