首页 > 解决方案 > 将双精度写入 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++ 代码,在我的树莓派上向 i2c 写入双精度。写一个 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);
}

标签: c++raspberry-pii2c

解决方案


推荐阅读