0

我是 I2C 通信的初学者,我正在尝试使用 librobotcontrol http://strawsondesign.com/docs/librobotcontrol/group___i2_c.html C 中的 i2c 库连接与 I2C 设备 a (mpu6050) 的通信。代码不包括东西与 I2C 无关,我有:

#define I2C_ADDRESS 0x68
#define I2C_BUS 1

void setupMPU();
float recordAccelRegisters();

int main(){

    float ax = 0;
    while(1){
        ax = recordAccelRegisters()
    }

    float recordAccelRegisters(){
        float Xg = 0;
        float Xa = 0, Ya, Za;
        unsigned char data;

        printf("Recording Accel Data\n");

        rc_i2c_init (I2C_BUS,I2C_ADDRESS);
        rc_i2c_read_bytes(I2C_BUS, 0x3B, 6, data);
        rc_i2c_close(I2C_BUS);

        //Xa = 8 << data;
        //Xa = (float)Xa;
        //Xg = Xa/16384.0;
        return Xg;
        }

    void setupMPU(){
        printf("Initalizing Mpu\n");

        // init I2C Bus
        rc_i2c_init (I2C_BUS,I2C_ADDRESS);

        //Wake up setup
        rc_i2c_write_byte(I2C_BUS, 0x6B, 0x00);
        rc_i2c_close(I2C_BUS);

        printf("Configuring Accelerometer\n");
        printf("Initalizing Mpu\n");

        //Accel Config
        rc_i2c_init (I2C_BUS,I2C_ADDRESS);
        rc_i2c_write_byte(I2C_BUS, 0x1C, 0x00);

        printf("Done with Accel Config\n");
        rc_i2c_close(I2C_BUS);
        }
   }

我试图弄清楚是否需要每次都关闭并重新打开端口,就像在使用线库的 Arduino 中一样,或者我是否可以只初始化一次。我尝试了许多不同类型的代码配置。例如只初始化一次通信,使用发送字而不是发送字节,一次只发送 1 个字节等......但我仍然无法从设备获取数据。我也在与天气作斗争,或者不使用读取的单词或读取的字节。使用时,它会不断返回 -1 字节,如此错误消息所示

读取字节:

ERROR: in rc_i2c_read_bytes, received -1 bytes from device, expected 1

使用读取单词时出现此错误:

ERROR: Segmentation Fault
Fault address: (nil)
Address not mapped.
Segmentation fault

对此的任何帮助将不胜感激。

4

1 回答 1

0

根据您链接的文档,该函数rc_i2c_read_bytes需要一个指针,它将存储读取的字节:

int rc_i2c_read_bytes (int bus, uint8_t regAddr, size_t count, uint8_t *data);
Reads multiple bytes from a device register

因此,在您的recordAccelRegisters函数中,您应该定义一个数组来存储字节:

float recordAccelRegisters(){
        float Xg = 0;
        float Xa = 0, Ya, Za;
        unsigned char data[6];

        printf("Recording Accel Data\n");

        rc_i2c_init (I2C_BUS,I2C_ADDRESS);
        rc_i2c_read_bytes(I2C_BUS, 0x3B, 6, data);
        rc_i2c_close(I2C_BUS);

        //Xa = 8 << data;
        //Xa = (float)Xa;
        //Xg = Xa/16384.0;
        return Xg;
}

如果您使用 ,同样适用rc_i2c_read_word,它还需要一个指针(指向 a uint16_t):

float recordAccelRegisters(){
        float Xg = 0;
        float Xa = 0, Ya, Za;
        uint16_t data;

        printf("Recording Accel Data\n");

        rc_i2c_init (I2C_BUS,I2C_ADDRESS);
        rc_i2c_read_word(I2C_BUS, 0x3B, &data);
        rc_i2c_close(I2C_BUS);

        //Xa = 8 << data;
        //Xa = (float)Xa;
        //Xg = Xa/16384.0;
        return Xg;
}

于 2022-02-23T04:40:08.997 回答