【问题标题】:Why is the I2C communication failing on a second pass through the same code?为什么第二次通过相同代码时 I2C 通信失败?
【发布时间】:2020-03-12 09:56:48
【问题描述】:

风景 - 我有一个执行大量任务的 MCU。它将 I2C 从机通信暴露给 Raspberry Pi。我在 MCU 上的代码中创建了许多“寄存器”。所有这些都工作正常。我之前有一个 nano 连接并测试了 MCU 上的所有东西,所以我相当确定 MCU 的行为是正确的。我的大部分 I2C 通信也在 Pi 上工作。除了一个。有点不同的是它写入了三个字节。

这是我的 RPi 代码:

std::string i2cServo(uint8_t reg, uint8_t angle){
    std::string error;
    uint8_t TxBuf[3];
    TxBuf[0] = 11;         // The register.
    TxBuf[1] = reg;        // The first parameter.
    TxBuf[2] = angle;      // The second parameter.
    close_fd();
    if (!fd) {
        if (open_fd_wronly() == -1) {
            error = "Failed to open I2C bus.";
        } else {
            if (write(fd, &TxBuf, 3) != 3) {
                std::cerr << errno << std::endl;
                error = "Could not set servo.";
            }
        }
    }
    return error;
}

这段代码被执行了两次。第一次一切正常,第二次我得到 errno 5。这是 EIO。

这是逻辑分析仪的输出:

你可以看到第一遍是好的。第二遍也很好,直到预计停止。

如果不是因为 nano 行为正确,我会怀疑 MCU,而且代码的第一遍运行良好。

有什么想法吗?

这是 fd 的开头:

int open_fd_wronly(){
    error_flag = false;
    if (fd) {
        close_fd();
        fd = 0;
    }
    if ((fd = open(devicefile.c_str(), O_WRONLY)) < 0)
        return errorMsg("ERROR opening: " + devicefile + "\n");
    if (ioctl(fd, I2C_SLAVE, slave_address) < 0)
        return errorMsg("ERROR address: " + std::to_string(slave_address) + "\n");
    return 0;
}

【问题讨论】:

  • “fd”在哪里初始化?
  • open_fd_wronly() ,我将编辑问题。

标签: raspberry-pi c++17 clion i2c unistd.h


【解决方案1】:

抱歉,问题未及时发布。答案让我恍然大悟。分享问题真的很有帮助。第一个寄存器调用提示写入 EEPROM,第二个调用刚刚到达太快,触发了另一个对 EEPROM 的写入并导致崩溃。两个电话之间的一点延迟解决了这个问题。 非常感谢。

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2020-08-04
    • 2015-09-01
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2019-09-07
    相关资源
    最近更新 更多