请注意,本文内容源自机器翻译,可能存在语法或其它翻译错误,仅供参考。如需获取准确内容,请参阅链接中的英语原文或自行翻译。
器件型号:CC1310 工具/软件:
在我的应用中、我有2个传感器连接到同一条 I2C 总线。 当我启动器件时、它会无错误地初始化 I2C、但当我尝试写入一个器件时、I2C 失败、这个错误是随机的 、因为有时会发生、我不知道为什么。
我在两条线路上都有10k 上拉电阻器、我确保一次只有一个传感器使用具有信标的 I2C。 我的代码在下面,但我认为这不是问题。
/*
* @brief Initializes the I2C driver.
* @return TRUE: error.
* FALSE: success.
*/
bool i2c_init() {
I2C_init();
I2C_Params_init(&i2c_params);
i2c_params.bitRate = I2C_100kHz;
i2c_params.transferMode = I2C_MODE_BLOCKING;
i2c = I2C_open(Board_I2C0, &i2c_params);
if (i2c == NULL)
return true;
return false;
}
/*
* @brief Writes data to register.
* @param addr Address of the slave device.
* @param reg Register to write into.
* @param data Values to write.
* @param data_len Amount of bytes to write.
* @return Status (true = success).
*/
bool i2c_write(const uint8_t addr, uint8_t reg, uint8_t *data, const size_t data_len) {
if (i2c == NULL || data == NULL || data_len == 0) {
return false;
}
uint8_t tx[16];
tx[0] = reg;
size_t i = 0;
for (i = 0; i < data_len; i++)
tx[i+1] = data[i];
uint32_t key = HwiP_disable();
i2c_transaction.slaveAddress = addr;
i2c_transaction.writeBuf = tx;
i2c_transaction.writeCount = data_len + 1;
i2c_transaction.readBuf = NULL;
i2c_transaction.readCount = 0;
bool status = I2C_transfer(i2c, &i2c_transaction);
HwiP_restore(key);
return status;
}
/*
* @brief Reads <data_len> bytes from a register.
* @param addr Address of the slave device.
* @param reg Register to start reading from.
* @param data Buffer where the read data will be stored.
* @param data_len Amount of bytes to read.
* @return Status (true = success).
*/
bool i2c_read(const uint8_t addr, uint8_t reg, uint8_t *data, const size_t data_len) {
if (i2c == NULL || data == NULL || data_len == 0) {
return false;
}
uint32_t key = HwiP_disable();
i2c_transaction.slaveAddress = addr;
i2c_transaction.writeBuf =
i2c_transaction.writeCount = 1;
i2c_transaction.readBuf = data;
i2c_transaction.readCount = data_len;
bool status = I2C_transfer(i2c, &i2c_transaction);
HwiP_restore(key);
return status;
}