Simvik

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]
0

Learn it first

  • I2C · Addressing, repeated start, clock stretching and bus recovery.

More I2C problems