我正在从陀螺仪读取数据,但数据恢复正常,但值不符合预期。我认为这是由于在寻找解决方案之后我的编码出错,我提出了一个帖子HERE,指出:


  确保正确读取输出寄存器,数据为
  2的补码中的16位值(即MSB是符号位,然后是15
  值的位)


这对我来说很混乱,我不确定我的编码是否按预期读取值。我正在使用wiringPi I2C库为Arduino转换现有代码以在Raspberry Pi上运行。我在下面有我的代码,我希望有人可以告诉我,如果他们看到读取2的恭维中16位值的正确尝试。在getGyroValues函数内部,是我可以看到的唯一位置。我的代码是否正确读取值?

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>

#include <wiringPi.h>
#include <wiringPiI2C.h>

#define CTRL_REG1 0x20
#define CTRL_REG2 0x21
#define CTRL_REG3 0x22
#define CTRL_REG4 0x23


int fd;
int x = 0;
int y = 0;
int z = 0;
int main (){



    fd = wiringPiI2CSetup(0x69); // I2C address of gyro
    wiringPiI2CWriteReg8(fd, CTRL_REG1, 0x1F); //Turn on all axes, disable power down
    wiringPiI2CWriteReg8(fd, CTRL_REG3, 0x08); //Enable control ready signal
    wiringPiI2CWriteReg8(fd, CTRL_REG4, 0x80); // Set scale (500 deg/sec)
    delay(100);                    // Wait to synchronize

void getGyroValues (){
    int MSB, LSB;

    LSB = wiringPiI2CReadReg16(fd, 0x28);
    MSB = wiringPiI2CReadReg16(fd, 0x29);
    x = ((MSB << 8) | LSB);

    MSB = wiringPiI2CReadReg16(fd, 0x2B);
    LSB = wiringPiI2CReadReg16(fd, 0x2A);
    y = ((MSB << 8) | LSB);

    MSB = wiringPiI2CReadReg16(fd, 0x2D);
    LSB = wiringPiI2CReadReg16(fd, 0x2C);
    z = ((MSB << 8) | LSB);
}

    for (int i=0;i<10;i++){
    getGyroValues();
    // In following Divinding by 114 reduces noise
    printf("Value of X is: %d\n", x / 114);
    printf("Value of Y is: %d\n", y / 114);
    printf("Value of Z is: %d\n", z / 114);
    int t = wiringPiI2CReadReg8(fd, 0x26);
    t = (t*1.8)+32;//convert Celcius to Fareinheit
    int a = wiringPiI2CReadReg16(fd,0x2B);
    int b = wiringPiI2CReadReg16(fd,0x2A);
    printf("Y_L equals: %d\n", a);
    printf("Y_H equals: %d\n", b);
    int c = wiringPiI2CReadReg16(fd,0x28);
    int d = wiringPiI2CReadReg16(fd,0x29);
    printf("X_L equals: %d\n", c);
    printf("X_H equals: %d\n", d);
    int e = wiringPiI2CReadReg16(fd,0x2C);
    int f = wiringPiI2CReadReg16(fd,0x2D);
    printf("Z_L equals: %d\n", e);
    printf("Z_H equals: %d\n", f);

    printf("The temperature is: %d\n\n\n", t);
    delay(500);
}
};

最佳答案

这是您可以轻松地将最高和最低有效字节(代表2的补码16位整数的一半)合并为一个int的方法:

int Bytes2Short(unsigned char msb, unsigned char lsb)
{
  long t = msb * 0x100L + lsb;
  if (t >= 32768)
    t -= 65536;
  return (int)t;
}

关于c - 2的补码中的16位值,令人困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15191768/

10-12 04:02