You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:运行Madgwick算法代码时出现madgwickahrs模块缺失错误

解决"ModuleNotFoundError: No module named 'madgwickahrs'"错误

1. 安装缺失的模块

你遇到的错误是因为Python环境未安装madgwickahrs库,直接在终端运行以下命令完成安装:

pip install madgwickahrs

如果你的系统同时存在Python2和Python3环境,改用pip3 install madgwickahrs确保安装到Python3.9环境中。

2. 修正代码中的问题

你的代码还有几处需要调整的细节:

  • self._ninedof.read()是设备读取的自定义逻辑,在独立脚本中self无法直接使用,需替换成你实际读取陀螺仪、加速度计、磁力计数据的代码;
  • 陀螺仪数据需要转换成弧度后传入update方法(你已定义gyr_rad但未实际使用);
  • 代码同时导入了两个不同库的Madgwick实现(ahrs.filters.Madgwick和madgwickahrs.MadgwickAHRS),建议只保留一种,避免逻辑混淆。

修正后的可运行示例

以下是基于madgwickahrs库的测试代码(用你提供的传感器数据模拟循环读取):

import numpy as np
from madgwickahrs import MadgwickAHRS

# 初始化MadgwickAHRS,可根据实际采样频率调整sampleperiod参数
heading = MadgwickAHRS(sampleperiod=1/50, beta=0.1)

while True:
    # 模拟读取传感器数据(实际使用时替换为设备读取逻辑)
    gyr = np.array([1.6, 0.6, 1.5]) * (np.pi/180)  # 陀螺仪数据转弧度
    acc = np.array([1.2, 1.9, 1.3])
    mag = np.array([2.1, 1.3, 2.1])
    
    # 更新姿态数据
    heading.update(gyr, acc, mag)
    
    # 将四元数转换为欧拉角(单位:弧度,如需角度可乘180/np.pi)
    roll, pitch, yaw = heading.quaternion.to_euler_angles()
    
    # 打印结果
    print(f"Roll: {roll:.2f} rad, Pitch: {pitch:.2f} rad, Yaw: {yaw:.2f} rad")

额外说明

如果你想使用ahrs库的Madgwick实现,只需保留from ahrs.filters import Madgwick,并按照该库的API编写代码,无需安装madgwickahrs库。两种库的调用逻辑不同,选择一种即可。

内容的提问来源于stack exchange,提问作者SAHAR GOHARSHENASAN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 20:22:53