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--

Some Insight into the code:-

If you look into i2c.c, you 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.

Let's CODE :)

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.
I am going to write the edited part only. If you want to download the full code, go to the end of the page.

uint8_t data[2];

data[0]= 'o';
data[1] = 'k';
HAL_I2C_Master_Transmit (&hi2c1, 0x4E, data, 2, 50); 

Here hi2c1 is the hi2c1 handler
         0x4E is the address of the slave
         data is data as defined above
         2 is the size of data in bytes
         50 is the timeout in ms in case of any error.

That's it guys. We will see how to interface LCD using I2C in next tutorial. Subscribe my blog for instant notification. Do watch my youtube videos to see the working of a real hardware.



To download full code, click  Download and to go to my youtube channel, click controllerstech
I2C in STM32 I2C in STM32 Reviewed by Controllerstech on July 07, 2017 Rating: 5

No comments:

Powered by Blogger.