Minor modifications to I2C functions

This commit is contained in:
dooku 2021-06-09 14:58:30 +02:00
parent a3bfe95c57
commit 4833a4fb99
2 changed files with 15 additions and 4 deletions

View File

@ -24,6 +24,8 @@
#define I2C_OK 0
#define I2C_ERROR -1 // generic error
#define I2C_ERROR_NACK -2 // NACK was received during transfer
#define I2C_ERROR_TX_INCOMPLETE -3 // number of TXed bytes != buffer length
#define I2C_ERROR_RX_INCOMPLETE -4 // number of RXed bytes != buffer length
/*
* Type definitions

View File

@ -20,9 +20,11 @@ int i2c_init(i2c_context_t *context)
int i2c_transmit(uint8_t address, uint8_t *buffer, int len)
{
LL_I2C_HandleTransfer(i2c_context->i2c, address, LL_I2C_ADDRESSING_MODE_7BIT, len,
LL_I2C_MODE_AUTOEND, LL_I2C_GENERATE_START_WRITE);
LL_I2C_HandleTransfer(i2c_context->i2c, address, LL_I2C_ADDRSLAVE_7BIT, len,
LL_I2C_MODE_AUTOEND, LL_I2C_GENERATE_START_WRITE);
int i = 0;
// Autoend mode will raise STOP flag if NACK is detected
// (or if desired number of bytes is transmitted)
while (!LL_I2C_IsActiveFlag_STOP(i2c_context->i2c)) {
if (LL_I2C_IsActiveFlag_TXE(i2c_context->i2c)) {
if (i < len) {
@ -34,12 +36,17 @@ int i2c_transmit(uint8_t address, uint8_t *buffer, int len)
if (LL_I2C_IsActiveFlag_NACK(i2c_context->i2c)) {
return I2C_ERROR_NACK;
}
if (len != i) {
// this will probably never happen, as NACK flag
// is raised everytime len != number of TXed bytes
return I2C_ERROR_TX_INCOMPLETE;
}
return I2C_OK;
}
int i2c_receive(uint8_t address, uint8_t *buffer, int len)
{
LL_I2C_HandleTransfer(i2c_context->i2c, address, LL_I2C_ADDRESSING_MODE_7BIT, len,
LL_I2C_HandleTransfer(i2c_context->i2c, address, LL_I2C_ADDRSLAVE_7BIT, len,
LL_I2C_MODE_AUTOEND, LL_I2C_GENERATE_START_READ);
int i = 0;
while (!LL_I2C_IsActiveFlag_STOP(i2c_context->i2c)) {
@ -50,6 +57,8 @@ int i2c_receive(uint8_t address, uint8_t *buffer, int len)
}
}
LL_I2C_ClearFlag_STOP(i2c_context->i2c);
if (len != i) {
return I2C_ERROR_RX_INCOMPLETE;
}
return I2C_OK; // TODO error detection
}