Read and Write I2C Registers With HAL_I2C_Mem_Read and HAL_I2C_Mem_Write
Use HAL_I2C_Mem_Read and HAL_I2C_Mem_Write on STM32 for sensor and EEPROM registers: shifted address, memory address size, timeouts and errors.

Almost every I2C chip is a set of registers: write a register number, then read or write its contents. The STM32 HAL wraps that whole pattern, including the repeated start, in one call each for reading and writing, HAL_I2C_Mem_Read and HAL_I2C_Mem_Write. They are the right default for sensors, real-time clocks and EEPROMs, and they hide a few details that cause the most common failures: the device address is passed in a shifted form, the memory address size must match the chip, and the return code distinguishes a missing device from a bus fault. This post uses STM32CubeF4 HAL v1.28 on an STM32F407 with I2C1, reads and writes an MPU-6050 and a 24C32 EEPROM, and covers errors, the interrupt and DMA variants and the EEPROM write-cycle wait. The protocol is in the guide to I2C in this cluster.
The signatures
HAL_StatusTypeDef HAL_I2C_Mem_Read (I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
uint16_t MemAddress, uint16_t MemAddSize,
uint8_t *pData, uint16_t Size, uint32_t Timeout);
HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
uint16_t MemAddress, uint16_t MemAddSize,
uint8_t *pData, uint16_t Size, uint32_t Timeout);| Parameter | Meaning |
|---|---|
hi2c | The handle from CubeMX, such as &hi2c1 |
DevAddress | The device address shifted left by one: 7-bit 0x68 is passed as 0x68 << 1, which is 0xD0 |
MemAddress | The register or memory address inside the device |
MemAddSize | I2C_MEMADD_SIZE_8BIT or I2C_MEMADD_SIZE_16BIT |
pData, Size | The data buffer and the number of bytes |
Timeout | Milliseconds; HAL_MAX_DELAY waits forever |
The shifted address is the single most common mistake. The HAL expects the 8-bit write form because it sets the direction bit itself by OR-ing in the read bit. Passing the plain 7-bit address 0x68 targets address 0x34, which usually does not exist, and the call returns HAL_ERROR with the acknowledge-failure code. Always define the address as a shifted constant:
#define MPU6050_ADDR (0x68u << 1)
#define EEPROM_ADDR (0x50u << 1)What the call does on the wire
HAL_I2C_Mem_Read produces the register-read sequence of the I2C guide in one call:
S | DevAddress+W | A | MemAddress | A | Sr | DevAddress+R | A | data ... | N | PFor a 16-bit MemAddSize it sends the high byte of the address first and then the low byte. For a write, HAL_I2C_Mem_Write sends the start, the address, the memory address and then the data bytes, followed by a stop. In both cases the HAL handles the ACK and NACK, including the NACK on the last byte read.
Register access on an MPU-6050
#include "stm32f4xx_hal.h"
#include <stdio.h>
extern I2C_HandleTypeDef hi2c1;
#define MPU6050_ADDR (0x68u << 1)
#define MPU_REG_WHO_AM_I 0x75
#define MPU_REG_PWR_MGMT1 0x6B
#define MPU_REG_ACCEL_X 0x3B
HAL_StatusTypeDef mpu_init(void)
{
uint8_t id = 0;
HAL_StatusTypeDef st;
st = HAL_I2C_Mem_Read(&hi2c1, MPU6050_ADDR, MPU_REG_WHO_AM_I,
I2C_MEMADD_SIZE_8BIT, &id, 1, 100);
if (st != HAL_OK) return st;
printf("WHO_AM_I = 0x%02X\n", id);
uint8_t wake = 0x00; /* clear SLEEP in PWR_MGMT_1 */
return HAL_I2C_Mem_Write(&hi2c1, MPU6050_ADDR, MPU_REG_PWR_MGMT1,
I2C_MEMADD_SIZE_8BIT, &wake, 1, 100);
}
HAL_StatusTypeDef mpu_read_accel(int16_t a[3])
{
uint8_t raw[6];
HAL_StatusTypeDef st = HAL_I2C_Mem_Read(&hi2c1, MPU6050_ADDR, MPU_REG_ACCEL_X,
I2C_MEMADD_SIZE_8BIT, raw, sizeof raw, 100);
if (st != HAL_OK) return st;
a[0] = (int16_t)((raw[0] << 8) | raw[1]);
a[1] = (int16_t)((raw[2] << 8) | raw[3]);
a[2] = (int16_t)((raw[4] << 8) | raw[5]);
return HAL_OK;
}With the board flat and still, calling mpu_init() and then printing a reading gives:
WHO_AM_I = 0x68
ax=-208 ay=96 az=16712The MPU-6050 sends the high byte first, so each pair combines as (high << 8) | low. At the default plus or minus 2 g range, 16384 counts are 1 g, and the Z value near 16384 means gravity is on the Z axis. Your numbers will vary.
Reading six consecutive registers in one call uses the sensor's register auto-increment, which is one transaction of about 100 microseconds at 400 kHz instead of six.
A 16-bit memory address: the 24C32 EEPROM
Serial EEPROMs of 4 KB and up use two address bytes, so MemAddSize is I2C_MEMADD_SIZE_16BIT. The 24C32 (4 KB) at 0x50 has a 32-byte page, a 5 ms internal write cycle and wraps writes inside a page.
#define EEPROM_ADDR (0x50u << 1)
#define EEPROM_PAGE 32u
HAL_StatusTypeDef eeprom_read(uint16_t addr, uint8_t *dst, uint16_t len)
{
return HAL_I2C_Mem_Read(&hi2c1, EEPROM_ADDR, addr,
I2C_MEMADD_SIZE_16BIT, dst, len, 200);
}
HAL_StatusTypeDef eeprom_write_page(uint16_t addr, const uint8_t *src, uint16_t len)
{
HAL_StatusTypeDef st = HAL_I2C_Mem_Write(&hi2c1, EEPROM_ADDR, addr,
I2C_MEMADD_SIZE_16BIT,
(uint8_t *)src, len, 200);
if (st != HAL_OK) return st;
/* wait for the internal write cycle: poll until the device acknowledges again */
return HAL_I2C_IsDeviceReady(&hi2c1, EEPROM_ADDR, 10, 20);
}
HAL_StatusTypeDef eeprom_write(uint16_t addr, const uint8_t *src, uint16_t len)
{
while (len > 0) {
uint16_t room = EEPROM_PAGE - (addr % EEPROM_PAGE);
uint16_t chunk = (len < room) ? len : room;
HAL_StatusTypeDef st = eeprom_write_page(addr, src, chunk);
if (st != HAL_OK) return st;
addr += chunk;
src += chunk;
len -= chunk;
}
return HAL_OK;
}HAL_I2C_IsDeviceReady(hi2c, DevAddress, Trials, Timeout) sends the address repeatedly until the device acknowledges, which an EEPROM does once its write cycle ends. It is the HAL's built-in acknowledge polling and returns HAL_OK when the device answers. The wrapper eeprom_write splits the data at the 32-byte page boundaries, because a write that crosses a page wraps to the start of the same page and corrupts it.
A round trip:
uint8_t out[16] = {0};
const uint8_t msg[] = "calibration v3";
eeprom_write(0x001C, msg, sizeof msg); /* crosses the 32-byte boundary at 0x20 */
eeprom_read(0x001C, out, sizeof msg);
printf("read back: %s\n", out);read back: calibration v3The 15 bytes starting at 0x1C cross the page boundary at 0x20, so the helper issues two writes of 4 and 11 bytes.
Return codes and error flags
The function returns a HAL_StatusTypeDef:
| Value | Meaning |
|---|---|
HAL_OK | Transfer finished |
HAL_ERROR | A bus error occurred, check hi2c->ErrorCode |
HAL_BUSY | The peripheral is already in a transfer |
HAL_TIMEOUT | The timeout expired |
When the status is HAL_ERROR, HAL_I2C_GetError(&hi2c1) returns the cause as bit flags:
void i2c_report_error(void)
{
uint32_t e = HAL_I2C_GetError(&hi2c1);
if (e & HAL_I2C_ERROR_AF) printf("no acknowledge (wrong address or absent device)\n");
if (e & HAL_I2C_ERROR_BERR) printf("bus error (misplaced start or stop, noise)\n");
if (e & HAL_I2C_ERROR_ARLO) printf("arbitration lost\n");
if (e & HAL_I2C_ERROR_OVR) printf("overrun\n");
if (e & HAL_I2C_ERROR_TIMEOUT) printf("hardware timeout\n");
}HAL_I2C_ERROR_AF is by far the most common and means the address was not acknowledged: the shifted-address mistake, a device without power or wrong wiring. After a bus error or a stuck bus, the peripheral may stay in the BUSY flag and every later call returns HAL_BUSY; deinitialize and reinitialize it with HAL_I2C_DeInit and HAL_I2C_Init, after freeing the lines with the nine-clock recovery covered in its own post.
Interrupt and DMA variants
Each function has non-blocking versions: HAL_I2C_Mem_Read_IT, HAL_I2C_Mem_Read_DMA and the same for write. They return immediately and signal completion through callbacks:
static volatile uint8_t mem_done;
void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c) { mem_done = 1; }
void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c) { mem_done = 1; }
void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c) { mem_done = 0xFF; }
HAL_StatusTypeDef mpu_read_accel_dma(uint8_t *raw6)
{
mem_done = 0;
return HAL_I2C_Mem_Read_DMA(&hi2c1, MPU6050_ADDR, MPU_REG_ACCEL_X,
I2C_MEMADD_SIZE_8BIT, raw6, 6);
}The buffer must stay valid until the callback runs, so it cannot be a local variable. The IT and DMA calls take no timeout, so guard against a hung bus yourself with a timer. Use the blocking calls for configuration at start-up and the DMA versions where a periodic sensor read must not stall the CPU.
Pitfalls
Unshifted address. The most common failure. Shift left by one in the constant.
**Wrong
MemAddSize.** An EEPROM that needs two address bytes but gets one returns garbage or writes to the wrong place; a sensor that needs one but gets two sends an extra byte into its first data register.Crossing a page in EEPROM writes. Split at page boundaries.
No write-cycle wait. Calling the next write immediately after the previous one returns an acknowledge failure until the cycle ends.
Reading a block that the device does not auto-increment. Some chips repeat the same register; check the datasheet.
Using the blocking call from an interrupt. It relies on
HAL_GetTickfor timeouts, so a call from an interrupt of higher priority than SysTick can hang.Concurrent use from two tasks. The HAL handle is not thread-safe; protect it with a mutex.
When HAL_I2C_Mem_* is not enough
A transaction that does not fit "address, memory address, data" falls outside it: a device whose registers are selected by a command byte followed by a write and a delayed read, a write of a command with no data, or a read that needs a pause between the write and read phases. Use HAL_I2C_Master_Transmit and HAL_I2C_Master_Receive for those, and for sequences with several repeated starts use HAL_I2C_Master_Seq_Transmit_IT and its siblings, or drop to registers. The HAL's older I2C implementation on the F4 also has known lock-up errata; a robust product adds the bus recovery and a watchdog.


