2013-03-03 112 views
3

我正在转换在特定的微控制器上运行的程序,并使其适应在树莓派上运行。我已经成功地从我一直在使用的传感器中获取值,但现在我遇到了一个问题,我认为这是由于我无法理解的几行代码造成的。我已经阅读了他们的内容,但仍然在挠头。下面的代码我相信应该修改存储在X,Y,Z变量中的数字,但我不认为这是发生在我当前的程序中。此外,我不得不将byte更改为INT以使程序编译时无错误。这是我转换的原始代码中的未修改代码。有人可以告诉我,这是甚至修改数字吗?理解MSB LSB

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 
} 

回答

5

I2C是用于跟低速外设一个两线协议。

您的传感器应通过I2C总线连接到您的CPU。你正在读取传感器的三个值 - 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 = 0×45 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); 
} 
+1

@ Yamaha32088 - 我已经编辑我的答案。让我知道它是否回答你所有的问题,或者如果你需要更多的具体细节。 – Tuxdude 2013-03-03 08:21:30