向I2C设备写入一个double

时间:2018-11-14 11:18:20

标签: c++ raspberry-pi i2c

当我尝试在模式为i2cset的raspberryPI上使用SMBus block data时,说的是Error: Adapter does not have SMBus block write capability

# sudo i2cset -y 3 0x20 0x01 0xDE 0xAD 0xC0 0xDE 0x00 0xFF s
Error: Adapter does not have SMBus block write capability

我查看了WiringPi代码,它具有2个在I2C上写入数据的功能。第一个使用字节数据,第二个使用字数据。它缺少(SMBus块数据)和(I2C块数据)。所以我想RaspberryPi不支持它。

我想实现一个C ++代码,该代码在raspberryPi上的i2c中写入一个double。要写一个已经在做的int。

root@sense4:~/i2c-tests# sudo i2cset -y 3 0x20 0x00 0x1f
root@sense4:~/i2c-tests# sudo i2cget -y 3 0x20 0x00
0x1f

C ++代码:

int I2CTools::write8(int value) {
    union i2c_smbus_data data;

    data.byte = value;

    return i2c_smbus_access(i2cFileDescriptor, I2C_SMBUS_WRITE, 0x00, I2C_SMBUS_BYTE_DATA, &data);
}
int I2CTools::read8() {

    union i2c_smbus_data data;

    if (i2c_smbus_access(i2cFileDescriptor, I2C_SMBUS_READ, 0x00, I2C_SMBUS_BYTE_DATA, &data))
        return -1;
    else
        return data.byte & 0xFF;
}

现在我想我必须像这样遍历该地址:

root@sense4:~/i2c-tests# sudo i2cset -y 3 0x20 0x00 0x1f ; sudo i2cset -y 3 0x20 0x01 0x85 ; sudo i2cset -y 3 0x20 0x02 0xeb ; sudo i2cset -y 3 0x20 0x03 0x51 ; sudo i2cset -y 3 0x20 0x04 0xb8 ; sudo i2cset -y 3 0x20 0x05 0x1e ; sudo i2cset -y 3 0x20 0x06 0x09 ; sudo i2cset -y 3 0x20 0x07 0x40
root@sense4:~/i2c-tests# sudo i2cget -y 3 0x20 0x00 ;sudo i2cget -y 3 0x20 0x01 ; sudo i2cget -y 3 0x20 0x02 ; sudo i2cget -y 3 0x20 0x03 ; sudo i2cget -y 3 0x20 0x04 ; sudo i2cget -y 3 0x20 0x05 ; sudo i2cget -y 3 0x20 0x06 ; sudo i2cget -y 3 0x20 0x07
0x1f
0x85
0xeb
0x51
0xb8
0x1e
0x09
0x40

但是在C ++中,当然...这对您有意义吗?我是i2c设备的新手,我想这是我在代码中要做的方向。谢谢!

int I2CTools::writeDouble(double value) {
    union i2c_smbus_data data;

    doubleToCharArray.original = value;

    std::cout << "\nBytes: ";
    for (unsigned long address = 0; address < sizeof(double); address++) {
        std::cout << (int) doubleToCharArray.output[address] << ' ';
        data.byte = (int) doubleToCharArray.output[address];
        // std::cout << hex(doubleToCharArray.output[address]) << ' ';
        i2c_smbus_access(i2cFileDescriptor, I2C_SMBUS_WRITE, address, I2C_SMBUS_BYTE_DATA, &data);
    }
    return 0;
}
double I2CTools::readDouble() {

    unsigned char charArray[sizeof(double)];
    std::cout << "\nBytes: ";
    for (unsigned long address = 0; address < sizeof(double); address++) {
        union i2c_smbus_data data;
        if (i2c_smbus_access(i2cFileDescriptor, I2C_SMBUS_READ, address, I2C_SMBUS_BYTE_DATA, &data)) {
            return -1;
        } else {
            std::cout << (int) data.byte << ' ';
            charArray[address] = data.byte;
        }
    }
    return *reinterpret_cast<double *>(charArray);
}

0 个答案:

没有答案