了解MSB LSB

时间:2013-03-03 07:41:47

标签: c raspberry-pi

我正在努力转换在特定微控制器上运行的程序,并使其适应在树莓派上运行。我已成功地从我一直使用的传感器中提取值,但现在我遇到了一个问题,我认为这是由几行代码引起的,我无法理解。我已经阅读了它们的内容,但仍在摸不着头脑。我相信下面的代码应该修改存储在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
}

1 个答案:

答案 0 :(得分:5)

I2C是一种2线协议,用于与低速外设通信。

您的传感器应通过I2C总线连接到CPU。而你正在从传感器中读取3个值 - x,y和z。可以从传感器访问这些值6 x 8-bit寄存器。

x - Addresses 0x28, 0x29
y - Addresses 0x2A, 0x2B
z - Addresses 0x2C, 0x2D
正如函数名所暗示的那样,

ReadI2C()从传感器读取给定地址的数据字节并返回正在读取的数据。 ReadI2C()中的代码取决于设备的I2C控制器的设置方式。

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

例如:

  

我们假设:MSB = 0x45 LSB = 0x89

     

MSB&lt;&lt; 8 = 0x4500

     

(MSB <&lt; 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);
}
相关问题