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.
- Start a 1-byte write without
AUTOEND, wait forTXIS(orNACKF), and sendreg. - Wait for
TC: the byte is out and the bus is still yours. - Program a read of
nbytes withAUTOENDandSTART: a repeated start, with no STOP in between. Take each byte fromRXDRwhenRXNEis set. - 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
- 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.
- Fix: every second transfer is cut short · A write routine leaves STOPF set, so the next transfer thinks it has already finished.
- HVAC controller: trust the humidity reading · Combine the bytes an I²C humidity sensor returns, check their CRC, and scale them.