使用LIS2DH12三轴加速度传感器检测震动与倾斜角度

项目上用到LIS2DH12检测震动告警,设备倾斜状态,原理图如下
使用LIS2DH12三轴加速度传感器检测震动与倾斜角度_第1张图片

要检测震动跟倾斜角度,配置LIS2DH12的相关寄存器即可,寄存器很多,这里只说明程序中使用到的

#define LIS2DH12_FROM_FS_2g_HR_TO_mg(lsb)  (float)((int16_t)lsb>>4)* 1.0f
#define LIS2DH12_FROM_FS_4g_HR_TO_mg(lsb)  (float)((int16_t)lsb>>4)* 2.0f
#define LIS2DH12_FROM_FS_8g_HR_TO_mg(lsb)  (float)((int16_t)lsb>>4)* 4.0f
#define LIS2DH12_FROM_FS_16g_HR_TO_mg(lsb) (float)((int16_t)lsb>>4)*12.0f
#define LIS2DH12_FROM_LSB_TO_degC_HR(lsb)  (float)((int16_t)lsb>>6)/4.0f+25.0f

/* iic 通讯相关操作 */
int32_t drv_lis2dh12_iic_write_byte(uint8_t addr, uint8_t data);
int32_t drv_lis2dh12_iic_read_byte(uint8_t addr, uint8_t* data);

/* lis2dh12 init 配置检测阈值与中断 */
int32_t drv_lis2dh12_init()
{
	/* Initialization of sensor */
	if(drv_lis2dh12_iic_write_byte(0x21, 0x01)) /* CTRL_REG2(21h): Filtered data and High-pass filter selection */
		return -1;
		
	if(drv_lis2dh12_iic_write_byte(0x22, 0x40)) /* CTRL_REG3(22h): IA1 interrupt on INT1 pin */
		return -1;
	
	if(drv_lis2dh12_iic_write_byte(0x23, 0x80)) /* CTRL_REG4(23h): Set Full-scale to +/-2g */
		return -1;
	
	/* Wakeup recognition enable */ 
	if(drv_lis2dh12_iic_write_byte(0x30, 0x2a)) /* INT1_CFG(30h): INT1 Configuration */
		return -1;
	
	if(drv_lis2dh12_iic_write_byte(0x32, 0x36)) /* INT1_THS(32h): INT1 Threshold set */
		return -1;
	
	if(drv_lis2dh12_iic_write_byte(0x33, 0x0)) /* INT1_DURATION(33h): INT1 Duration set */
		return -1;
	
	/* Start sensor */
	if(drv_lis2dh12_iic_write_byte(0x20, 0x57)) /* CTRL_REG1(20h): Start sensor at ODR 100Hz Low-power mode */ 
		return -1;
	
	return 0;
}

/* 获取当前倾斜角度 */
float drv_lis2dh12_get_angle()
{
	float acc_x, acc_y, acc_z, acc_g;
	float angle_x, angle_y, angle_z, angle_xyz;
	int8_t data[6];
	uint8_t i;
	
	for (i=0; i<6; i++)
		drv_lis2dh12_iic_read_byte(0x28 + i, data+i);
	
	/* x, y, z 轴加速度 */
	acc_x = abs(LIS2DH12_FROM_FS_2g_HR_TO_mg(*(int16_t*)data));
	acc_y = abs(LIS2DH12_FROM_FS_2g_HR_TO_mg(*(int16_t*)(data+2)));
	acc_z = abs(LIS2DH12_FROM_FS_2g_HR_TO_mg(*(int16_t*)(data+4)));
	
	/* 重力加速度 */
	acc_g = sqrt(pow(acc_x, 2) + pow(acc_y, 2) + pow(acc_z, 2));
	
	if (acc_z > acc_g)
		acc_z = acc_g;

	/* angle_z/90 = asin(acc_z/acc_g)/π/2 */
	angle_z = asin(acc_z/acc_g) * 2 / 3.14 * 90;
	angle_z = 90 - angle_z;
	if(angle_z < 0)
		angle_z = 0;

	return angle_z;
}

你可能感兴趣的:(MCU)