From a50a181b862b422d25616c9eb2be97f3ebf6deb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?King=20K=C3=A9vin?= Date: Tue, 26 Mar 2019 18:12:21 +0100 Subject: [PATCH] I2C: fix read NACK NACKing in receive mode is different when 1, 2, or more bytes are read. see the reference manual for the cases and how to handle them. --- lib/i2c_master.c | 19 +++++++++++++++++-- lib/i2c_master.h | 1 + 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/i2c_master.c b/lib/i2c_master.c index 8d2cf1f..93bf078 100644 --- a/lib/i2c_master.c +++ b/lib/i2c_master.c @@ -417,7 +417,18 @@ enum i2c_master_rc i2c_master_read(uint32_t i2c, uint8_t* data, size_t data_size // sanity check if (data==NULL || data_size==0) { // no data to read return I2C_MASTER_RC_NONE; - } + } + if (1 == data_size) { + i2c_nack_current(i2c); // [N]ACK current byte + i2c_disable_ack(i2c); // NACK after first byte + } else if (2 == data_size) { + i2c_nack_next(i2c); // [N]ACK next byte + i2c_enable_ack(i2c); // NACK first byte + } else { + i2c_nack_current(i2c); // ACK current byte + i2c_enable_ack(i2c); // NAK after next byte + } + // reading SR2 will also also clear ADDR and start the transaction if (!(I2C_SR2(i2c) & I2C_SR2_MSL)) { // I2C device is not master return I2C_MASTER_RC_NOT_MASTER; } @@ -430,7 +441,11 @@ enum i2c_master_rc i2c_master_read(uint32_t i2c, uint8_t* data, size_t data_size // read data for (size_t i=0; i