Simvik

Driver: read registers with a repeated start

Write a register address, then read bytes back without releasing the bus in between. A medium embedded C problem (I2C), run and graded in the browser.

medium · I2C · driver · registers · i2c · repeated-start

Write i2c_read_reg(addr, reg, buf, n), the read every I2C sensor and EEPROM driver needs: send the register (or memory) address reg to the device at addr, then read n bytes (1 to 255) into buf. The bus is simulated like an STM32 G0's I2C with a 24C02 EEPROM at 0x50, and each transfer is reported when it ends.

  1. Start a 1-byte write without AUTOEND, wait for TXIS (or NACKF), and send reg.
  2. Wait for TC: the byte is out and the bus is still yours.
  3. Program a read of n bytes with AUTOEND and START: a repeated start, with no STOP in between. Take each byte from RXDR when RXNE is set.
  4. Wait for STOPF, clear it, return 0.

If the address is not acknowledged, the hardware sends a STOP on its own: wait for STOPF, clear NACKF and STOPF, and return -1.

Starter code

int i2c_read_reg(uint8_t addr, uint8_t reg, uint8_t *buf, int n) {
  return -1;
}

Example tests

Read three bytes back

i2c_init();
preload(0x20, "Hi!");
uint8_t buf[3];
printf("%d\n", i2c_read_reg(EEPROM_ADDR, 0x20, buf, 3));
printf("%c%c%c\n", buf[0], buf[1], buf[2]);

Expected output:

i2c1: write 0x50 [0x20 0x48 0x69 0x21]
i2c1: 0x50 nack
i2c1: write 0x50 []
i2c1: write 0x50 [0x20]
i2c1: read 0x50 [0x48 0x69 0x21]
0
Hi!

Learn it first

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

More I2C problems