How to Use I2C in STM32

Description

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

6.) Now Open the project and edit the code.

Some Insight into the code:-

If you look into i2c.cyou will find

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

100%
100%

DOWNLOAD

You can buy me a coffee sensor 🙂

download the CODE below

, , , ,

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
simone dallaiRosie Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Rosie
Guest
Rosie

M glad to finally found a working code. Thank you very much. 🙂

simone dallai
Guest
simone dallai

I tried to look everywhere if there was an i2c + dma tutorial in circular way but I didn’t find anything !!!if you have a tutorial please send it to me

Menu