</>EmbeddedInterview

Write I2C register read and write functions.

Medium"Coding: Embedded Drivers, Buffers & Schedulers"
#include <stdint.h>
#include <stddef.h>

/* Portable version on top of a bus primitive: write `wlen` bytes then (repeated START) read `rlen`.
   On Linux, the same primitive is the I2C_RDWR ioctl; on MCUs it wraps the I2C peripheral. */
int i2c_xfer(uint8_t addr7, const uint8_t *w, size_t wlen, uint8_t *r, size_t rlen);

int i2c_write_reg(uint8_t addr, uint8_t reg, const uint8_t *data, size_t len)
{
    uint8_t buf[1 + 16];
    if (len > 16) return -1;
    buf[0] = reg;                                     /* register address first */
    for (size_t i = 0; i < len; i++) buf[1 + i] = data[i];
    return i2c_xfer(addr, buf, 1 + len, NULL, 0);     /* START, addr+W, reg, data..., STOP */
}

int i2c_read_reg(uint8_t addr, uint8_t reg, uint8_t *data, size_t len)
{
    return i2c_xfer(addr, &reg, 1, data, len);        /* START, addr+W, reg, RESTART, addr+R, data..., NACK, STOP */
}

/* Linux user-space implementation of the primitive */
#ifdef __linux__
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
extern int g_i2c_fd;                                  /* open("/dev/i2c-1", O_RDWR) */

int i2c_xfer(uint8_t addr7, const uint8_t *w, size_t wlen, uint8_t *r, size_t rlen)
{
    struct i2c_msg msgs[2];
    int n = 0;
    if (wlen) msgs[n++] = (struct i2c_msg){ .addr = addr7, .flags = 0, .len = (uint16_t)wlen, .buf = (uint8_t *)w };
    if (rlen) msgs[n++] = (struct i2c_msg){ .addr = addr7, .flags = I2C_M_RD, .len = (uint16_t)rlen, .buf = r };
    struct i2c_rdwr_ioctl_data d = { .msgs = msgs, .nmsgs = (uint32_t)n };
    return ioctl(g_i2c_fd, I2C_RDWR, &d) == n ? 0 : -1;
}
#endif

Points: a register read is a write of the register address followed by a repeated START and a read (no STOP in between, or some devices lose the address); the controller NACKs the last byte to tell the target to stop sending; check for NACK on the address (device missing) and on data; add timeouts and bus recovery (clock out 9 pulses if SDA is stuck low); respect the device's maximum burst length and page boundaries (EEPROMs); 16-bit register addresses send two address bytes, usually MSB first.