turnDetection(4285).c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "turnDetection.h"
  2. //--------------------------define
  3. // 定义转弯阈值
  4. #define TURNING_THRESHOLD 1.0 // 以角度为单位,这个值需要根据实际情况调整
  5. // 低通滤波参数
  6. #define ALPHA 0.9 // 这个值需要根据实际情况调整
  7. //--------------------------param
  8. // 初始化姿态角度和角速度
  9. float previousPitch = 0.0;
  10. float previousRoll = 0.0;
  11. float previousYaw = 0.0;
  12. float previousAngularVelocity = 0.0;
  13. // 转弯标志
  14. uint8_t turnFlag = 0;
  15. /**
  16. * @brief 将陀螺仪值转换为角速度值
  17. * @param none
  18. * @note
  19. * @retval angle:角速度值
  20. */
  21. float getAngularVelocity(void)
  22. {
  23. int16_t gyroscopeData[3] = {0};
  24. // // 读取陀螺仪数据
  25. atk_ms6050_get_gyroscope(&gyroscopeData[0], &gyroscopeData[1], &gyroscopeData[2]);
  26. // 计算陀螺仪数据的模长(即角速度)
  27. float gyroMagnitude = sqrt(pow(gyroscopeData[0], 2) + pow(gyroscopeData[1], 2) + pow(gyroscopeData[2], 2));
  28. return gyroMagnitude;
  29. }
  30. // 低通滤波函数
  31. float lowPassFilter(float previousValue, float rawValue) {
  32. return ALPHA * previousValue + (1 - ALPHA) * rawValue;
  33. }
  34. // 判断车辆是否正在转弯的函数
  35. int isTurning(void) {
  36. // 获取当前的 pitch、roll 和 yaw 角度
  37. float roll = 0.0, pitch = 0.0, yaw = 0.0;
  38. atk_ms6050_dmp_get_data(&pitch, &roll, &yaw);
  39. printf("pitch:%.1f\n", pitch);
  40. printf("roll:%.1f\n", roll);
  41. printf("yaw:%.1f\n", yaw);
  42. // 获取当前的角速度
  43. float angularVelocity = getAngularVelocity();
  44. // 应用低通滤波
  45. pitch = lowPassFilter(previousPitch, pitch);
  46. roll = lowPassFilter(previousRoll, roll);
  47. yaw = lowPassFilter(previousYaw, yaw);
  48. angularVelocity = lowPassFilter(previousAngularVelocity, angularVelocity);
  49. // 计算姿态角度的变化速度
  50. float pitchChangeRate = fabs(pitch - previousPitch);
  51. float rollChangeRate = fabs(roll - previousRoll);
  52. float yawChangeRate = fabs(yaw - previousYaw);
  53. printf("pitchChangeRate:%.1f\n", pitchChangeRate);
  54. printf("rollChangeRate:%.1f\n", rollChangeRate);
  55. printf("yawChangeRate:%.1f\n", yawChangeRate);
  56. // 判断车辆是否正在转弯
  57. if (pitchChangeRate > TURNING_THRESHOLD || rollChangeRate > TURNING_THRESHOLD || yawChangeRate > TURNING_THRESHOLD) {
  58. turnFlag = 1; // 表示车辆正在转弯
  59. } else {
  60. turnFlag = 0; // 表示车辆未转弯
  61. }
  62. // 更新上一次的姿态角度和角速度
  63. previousPitch = pitch;
  64. previousRoll = roll;
  65. previousYaw = yaw;
  66. previousAngularVelocity = angularVelocity;
  67. if(turnFlag == 1){
  68. return 1;
  69. }else{
  70. return 0;
  71. }
  72. }