gpt4 book ai didi

c - 了解 MSB LSB

转载 作者:太空狗 更新时间:2023-10-29 16:13:13 30 4
gpt4 key购买 nike

我正在努力转换在特定微 Controller 上运行的程序,并使其适应在树莓派上运行。我已经成功地从我一直在使用的传感器中提取值,但现在我遇到了一个问题,我认为这是由我无法理解的几行代码引起的。我已经阅读了它们是什么,但仍在摸不着头脑。我认为下面的代码应该修改存储在 X,Y,Z 变量中的数字,但是我认为这不会发生在我当前的程序中。此外,我还必须将 byte 更改为 INT 以使程序编译无误。这是我转换的原始代码中未修改的代码。有人能告诉我这是否在修改号码吗?

void getGyroValues () {
byte MSB, LSB;

MSB = readI2C(0x29);
LSB = readI2C(0x28);
x = ((MSB << 8) | LSB);

MSB = readI2C(0x2B);
LSB = readI2C(0x2A);
y = ((MSB << 8) | LSB);

MSB = readI2C(0x2D);
LSB = readI2C(0x2C);
z = ((MSB << 8) | LSB);
}

这是原始的 readI2C 函数:

int readI2C (byte regAddr) {
Wire.beginTransmission(Addr);
Wire.write(regAddr); // Register address to read
Wire.endTransmission(); // Terminate request
Wire.requestFrom(Addr, 1); // Read a byte
while(!Wire.available()) { }; // Wait for receipt
return(Wire.read()); // Get result
}

最佳答案

I2C是一种用于与低速外设通信的 2 线协议(protocol)。

您的传感器应通过 I2C 总线连接到您的 CPU。您正在从传感器读取 3 个值 - x、y 和 z。这些值可作为 6 x 8 位 寄存器从传感器访问。

x - Addresses 0x28, 0x29
y - Addresses 0x2A, 0x2B
z - Addresses 0x2C, 0x2D

ReadI2C() 正如函数名称所暗示的那样,从您的传感器的给定地址读取一个字节的数据并返回正在读取的数据。 ReadI2C() 中的代码取决于您设备的 I2C Controller 的设置方式。

一个字节是 8 位数据。 MSB(Most-Significant-Byte)和 LSB(Least-Significant-Byte)分别表示通过 I2C 读取的 8 位。看起来您对 16 位数据(对于 x、y 和 z)感兴趣。要从 2 段 8 位数据构造 16 位数据,您将 MSB 向左移动 8 位,然后与 LSB< 执行逻辑或运算.

例如:

Let us assume: MSB = 0x45 LSB = 0x89

MSB << 8 = 0x4500

(MSB << 8) | LSB = 0x4589

同时查看我的内联评论:

void getGyroValues () {
byte MSB, LSB;

MSB = readI2C(0x29);
LSB = readI2C(0x28);
// Shift the value in MSB left by 8 bits and OR with the 8-bits of LSB
// And store this result in x
x = ((MSB << 8) | LSB);

MSB = readI2C(0x2B);
LSB = readI2C(0x2A);
// Do the same as above, but store the value in y
y = ((MSB << 8) | LSB);

MSB = readI2C(0x2D);
LSB = readI2C(0x2C);
// Do the same as above, but store the value in z
z = ((MSB << 8) | LSB);
}

关于c - 了解 MSB LSB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15183530/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com