Fix: every second transfer is cut short
A write routine leaves STOPF set, so the next transfer thinks it has already finished. A medium embedded C problem (I2C), run and graded in the browser.
medium · I2C · find-the-bug · driver · i2c · flags
Bug report. i2c_write(addr, data, n) sends n bytes to the device at addr and returns 0, or -1 when the device does not answer. The first transfer after start-up always works. After that, transfers return before their bytes are on the bus, and the next one starts in the middle of the previous one. The I2C block is simulated like an STM32 G0's; each transfer is reported when it ends. Fix it by changing one line.
Starter code
int i2c_write(uint8_t addr, const uint8_t *data, int n) {
I2C1->CR2 = I2C_CR2_SADD(addr) | I2C_CR2_NBYTES(n) | I2C_CR2_AUTOEND | I2C_CR2_START;
for (int i = 0; i < n; i++) {
while (!(I2C1->ISR & (I2C_ISR_TXIS | I2C_ISR_NACKF))) {
}
if (I2C1->ISR & I2C_ISR_NACKF) break;
I2C1->TXDR = data[i];
}
while (!(I2C1->ISR & I2C_ISR_STOPF)) {
}
int nack = (I2C1->ISR & I2C_ISR_NACKF) != 0;
I2C1->ICR = I2C_ICR_NACKCF;
return nack ? -1 : 0;
}Example tests
Set the EEPROM's address pointer twice
i2c_init();
uint8_t a[] = { 0x00 }, b[] = { 0x10 };
printf("%d\n",i2c_write(EEPROM_ADDR, a, 1));
printf("%d\n",i2c_write(EEPROM_ADDR, b, 1));
printf("%d\n",i2c_write(EEPROM_ADDR, a, 1));Expected output:
i2c1: write 0x50 [0x00]
0
i2c1: write 0x50 [0x10]
0
i2c1: write 0x50 [0x00]
0Learn it first
- I2C · Addressing, repeated start, clock stretching and bus recovery.
More I2C problems
- Scan the bus · Find every device on the bus without probing the reserved addresses.
- Read a 16-bit register · Write the register pointer, read two bytes back with a repeated start, and handle a NACK.
- Recover a stuck bus · Clock a stuck device out with up to nine pulses, then send a STOP.
- Size the pull-up resistors · Work out the smallest and largest pull-up that meet the I2C specification.
- Driver: write an EEPROM over I2C, with ACK polling · Send an I2C write with the hardware's byte-by-byte handshake, then poll until the EEPROM finishes writing.
- Driver: read registers with a repeated start · Write a register address, then read bytes back without releasing the bus in between.
- HVAC controller: trust the humidity reading · Combine the bytes an I²C humidity sensor returns, check their CRC, and scale them.