Read a 16-bit register
Write the register pointer, read two bytes back with a repeated start, and handle a NACK. A medium embedded C problem (I2C), run and graded in the browser.
medium · I2C · i2c · drivers · errors
Most I2C sensors use a register pointer: you write the register number, then read the data back after a repeated start.
Write read_reg16(addr, reg, value):
- write the one-byte register number with no STOP (
stop = false), - read two bytes; the first is the most significant,
- return
I2C_OKand store the 16-bit value in*value.
If either transfer fails, return its error straight away and leave *value unchanged: the caller keeps its last good value.
Starter code
i2c_err_t read_reg16(uint8_t addr, uint8_t reg, uint16_t *value) {
uint8_t buf[2] = {0, 0};
i2c_write(addr, ®, 1, false);
i2c_read(addr, buf, 2);
*value = (uint16_t)(buf[0] | (buf[1] << 8));
return I2C_OK;
}Example tests
Two registers
show(0x48, 0);
show(0x48, 2);Expected output:
error 0, value 0x1940
error 0, value 0x4B00A missing device
show(0x49, 0);Expected output:
error 1, value 0xDEADLearn 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.
- 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.
- 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.