STM32 Guide: I2C
Image for post

Prerequisites

This is tutorial is not intended to be a guide for learning C language or about the STM32 platform. It’s primary target is to provide developers a concise guide about integrating peripheral modules and features into active applications.

If you are a beginner, I would recommend you look into an STM32 Project Setup guide like this one.

https://medium.com/vicara-hardware-university/smt32-project-setup-with-cubeide-947974baf713

I2C

I2C uses two wires/connection channels, the clock and data commonly referred to as SCL and SDA respectively. This protocol allows communication of a single master device with multiple slave devices. Differentiation is done either by address of the slave device, or using a GPIO pin to enable only a single device at a time.

I2C may interchangeably be used in the same context as TWI (Two Wire Interface).

I2C in STM32

The initialization process for STM32 peripherals is handled by the Cube IDE. Once that is done, the code generator gives a main.c file with the I2C_Init() function configured as per the settings you mention in the Cube IDE File.

Image for post


Image for post


Fig.3 I2C Configuration

In the F407 Dev Kit we have I2C1 enabled by default. The generated code will therefore have I2C1_Init() function in the main.c file and also have it called.

The configuration will follow the same parameters you have set in the Peripheral Config Tab.

The generator will also create an I2C typedef handle. We can now use I2C API functions by using this handle as a reference.

I2C in STM32 can be done in 3 methods.

  1. Blocking Mode
  2. Interrupt Mode
  3. DMA Mode

I2C HAL API Functions

Transmit Data

HAL_I2C_Master_Transmit(I2C_HandleTypeDef * hi2c, uint16_t DevAddress, uint8_t * pData, uint16_t Size, uint32_t Timeout)

Parameters

Parameters
* hi2c: Pointer to a I2C_HandleTypeDef structure that contains the configuration information for the specified I2C.
* DevAddress: Target device address: The device 7 bits
address value in datasheet must be shift at right before call
interface
* pData: Pointer to data buffer
* Size: Amount of data to be sent
* Timeout: Timeout duration
Return values
* HAL: status

Receive Data

HAL_I2C_Master_Receive(I2C_HandleTypeDef * hi2c, uint16_t DevAddress, uint8_t * pData, uint16_t Size, uint32_t Timeout)

Parameters

Parameters
* hi2c: Pointer to a I2C_HandleTypeDef structure that contains
the configuration information for the specified I2C.
* DevAddress: Target device address: The device 7 bits
address value in datasheet must be shift at right before call
interface
* pData: Pointer to data buffer
* Size: Amount of data to be sent
* Timeout: Timeout duration
Return values
* HAL: status

Conclusion

In this tutorial, we discussed the methods for using I2C API from CMSIS-HAL library for reading and writing to I2C devices.

Sources