From 4833a4fb99c34832b40fecf9a72345b0dbc20d3f Mon Sep 17 00:00:00 2001 From: dooku Date: Wed, 9 Jun 2021 14:58:30 +0200 Subject: [PATCH] Minor modifications to I2C functions --- fw/Core/Inc/i2c.h | 2 ++ fw/Core/Src/i2c.c | 17 +++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/fw/Core/Inc/i2c.h b/fw/Core/Inc/i2c.h index f655255..f346e68 100644 --- a/fw/Core/Inc/i2c.h +++ b/fw/Core/Inc/i2c.h @@ -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 diff --git a/fw/Core/Src/i2c.c b/fw/Core/Src/i2c.c index ed52827..57f999f 100644 --- a/fw/Core/Src/i2c.c +++ b/fw/Core/Src/i2c.c @@ -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 }