Simvik

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_OK and 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, &reg, 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 0x4B00

A missing device

show(0x49, 0);

Expected output:

error 1, value 0xDEAD

Learn it first

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

More I2C problems