【问题标题】:obtaining correct IMU values获得正确的 IMU 值
【发布时间】:2019-08-19 18:21:34
【问题描述】:

我正在使用 Python 2.7 通过 USB 从 AHRS / IMU 传感器读取数据。根据下图获取厂家规定的加速度:

供应商描述 IMU

我在 python 中的代码是这样的,但是当加速度为负时,值是错误的。 我相信我需要检查 MSB 的第一位(在本例中为 AxH 字段),如果 1 是负数,如果 0 是正数。

    #....
    #data = serial.read(size=11)
    #....
    #

    #Acceleration
    elif data[1] == b'\x51':
        AxL=int(data[2:3].encode('hex'), 16)
        AxH=int(data[3:4].encode('hex'), 16)
        AyL=int(data[4:5].encode('hex'), 16)
        AyH=int(data[5:6].encode('hex'), 16)
        AzL=int(data[6:7].encode('hex'), 16)
        AzH=int(data[7:8].encode('hex'), 16)

        x = (AxH<<8|AxL)/32768.0*16.0
        y = (AyH<<8|AyL)/32768.0*16.0
        z = (AzH<<8|AzL)/32768.0*16.0

大家有什么建议吗?

完整的 IMU 传感器手册是这样的: http://wiki.wit-motion.com/english/lib/exe/fetch.php?media=module:wt901:docs:jy901usermanualv4.pdf

【问题讨论】:

  • 不需要将数据转换为十六进制字符串,然后再转换回int。如果你在 Python3 中索引一个 bytes 对象,你会直接将(unisgned)字节作为一个 int,所以你可以只使用 AxL = data[2]。在 Python2 中,您必须这样做 AxL = ord(data[2])
  • 看我的回答,数据中shorts的有符号数表示很可能是two's complement,所以只使用MSB作为符号位是不正确的。

标签: python imu


【解决方案1】:

使用struct

坐标区数据存储为little-endiansigned short (2 byte) integers,因此我们可以使用struct 来解包数据。 struct 模块将负责将 bytes 正确解释为短整数。

import struct

g = 9.81
conv = 16.0 / 32768.0 * g

# ...

    elif data[1] == b'\x51':
        axes = struct.unpack("<hhh", data[2:8])
        x, y, z = [a*conv for a in axes]

手动转换

如果您想自己进行转换,我假设签名数字的表示是two's complement

def twos_complement(x, bytes=2):
    maxnum = 2**(bytes*8) - 1
    msb = 1 << (bytes*8 - 1) 
    return -((x^maxnum) + 1) if x&msb else x

AxL = data[2]
AxH = data[3]
Ax_unsigned = AxH << 8 | AxL
Ax = twos_complement(Ax_unsigned, 2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 2020-02-23
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多