How to Use I2C in STM32

So here I am starting I2C tutorial in STM32. I know it’s early because we still need to go through some basic things before jumping to I2C but the problem is LCD. It takes a whole lot of efforts to interface LCD using conventional methods, but by using I2C, we can do it really easy. I will cover other ways to interface LCD later in upcoming tutorials. Before using I2C to interface LCD, let’s first write a simple code to know about I2C functions.

I will use STM32CubeMX as usual to generate skeleton, and than edit it later. So follow along–

1.)  Start STM32CubeMX and create a new project, select your board.

2.) Select I2Cx. Here x can be 1,2,or 3 depending on your board.


3.) My final setup looks like this


4.) Now go to configuration and select I2Cx.


5.) Make sure that your I2C setup is as follows


Some Insight into the code:-

Here is the function that we are going to use

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

HAL_I2C_Master_Transmit is used for transmitting data to the I2C device. It takes following arguments--

I2C_HandleTypeDef *hi2c //is the pointer to the i2c handler.
uint16_t DevAddress //is the Address of the I2C device
uint8_t *pData  //is the pointer to the data to be transmitted 
uint16_t Size  //is the size of the data in bytes
uint32_t Timeout //timeout in case of any error

This is the only function I am going to use for now. When we will advance in these tutorials, I will show you how to use dma (HAL_I2C_Master_Transmit_DMA) and interrupt (HAL_I2C_Master_Transmit_IT) to send and receive data from an I2C device.

Result

Check out the VIDEO Below


. . . . . DOWNLOAD . . . . .

You can buy me a coffee Sensor by clicking DONATE OR Just click DOWNLOAD to download the code

controllerstech
100%
100%
Subscribe
Notify of
guest
2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Menu