The best tools to make your project dreams come true

Login or Signup
USD


By ShawnHymel

Getting Started with STM32 - I2C Example

The STM32 line of microcontrollers are a popular implementation of the ARM Cortex-M core from STMicroelectronics. As with most microcontrollers, almost all STM32 parts come equipped with 1 (or more!) I2C interfaces. 

If you have not set up STM32CubeIDE with your Nucleo board, you will need to do so following the steps outlined in this tutorial.

If video is your preferred medium, check out this video for how to use I2C with STM32:

 

Required Components

You will need the following components to complete this tutorial: https://www.digikey.com/short/p59jrr

Note that any Nucleo board may be used, but steps are shown for the Nucleo-L476RG.

TMP102 and I2C

The TMP102 is an extremely simple digital temperature sensor from Texas Instruments. It relies on I2C to communicate data to and from a host device. I recommend the SparkFun TMP102 Breakout Board to test the device.

Inter-Integrated Circuit (I2C) is a communication bus protocol developed by Philips Semiconductor (now NXP Semiconductors) in 1982. It is a relatively slow protocol but has seen widespread use due to its simplicity and robustness. Most microcontrollers have at least 1 I2C peripheral controller built in to the silicon.

If you would like to learn more about the I2C protocol, I recommend this tutorial from SparkFun.

By looking at the TMP102 datasheet, we can determine that retrieving temperature data from the temperature register would require a set of I2C write/read commands as follows:

TMP102 I2C Protocol

Note that we need to first send out a write command from the STM32 to the TMP102 with 1 byte that contains the address of the temperature register in the TMP102 (address 0x00). We immediately follow that with a read command where we read 2 bytes from the TMP102. These 2 bytes will contain the temperature data.

Hardware Hookup

Connect your Nucleo to the TMP102 as shown in the following Fritzing diagram:

Fritzing diagram of STM32 and TMP102

Create a New Project in STM32CubeIDE

Open STM32CubeIDE and click File > New > STM32 Project. Select the Nucleo-L476RG (or your preferred board) and name your project. Stick with the C target language. In the Pinout & Configuration window, assign PB8 and PB9 to I2C1_SCL and I2C1_SDA functions, respectively.

STM32CubeIDE pin selection

The pins should be colored yellow, which indicates that while the pins are assigned to a peripheral, that peripheral has not yet been initialized in the CubeMX software. On the left pane in CubeMX, select Categories > Connectivity > I2C1. In the Mode pane, change I2C Disable to I2C.

STM32CubeIDE pin selection

You should see the PB8 and PB9 pins turn green, indicating that we’ve fully configured the I2C peripheral.

Click File > Save and click Yes to generate code.

The Code

Open up main.c, and modify it to look like the following:

Copy Code
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>&copy; Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <string.h>
#include <stdio.h>
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c1;

UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */
static const uint8_t TMP102_ADDR = 0x48 << 1; // Use 8-bit address
static const uint8_t REG_TEMP = 0x00;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_I2C1_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
HAL_StatusTypeDef ret;
uint8_t buf12;
int16_t val;
float temp_c;
/* USER CODE END 1 */


/* MCU Configuration--------------------------------------------------------*/

/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();

/* USER CODE BEGIN Init */

/* USER CODE END Init */

/* Configure the system clock */
SystemClock_Config();

/* USER CODE BEGIN SysInit */

/* USER CODE END SysInit */

/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART2_UART_Init();
MX_I2C1_Init();
/* USER CODE BEGIN 2 */

/* USER CODE END 2 */

/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{

// Tell TMP102 that we want to read from the temperature register
buf0 = REG_TEMP;
ret = HAL_I2C_Master_Transmit(&hi2c1, TMP102_ADDR, buf, 1, HAL_MAX_DELAY);
if ( ret != HAL_OK ) {
strcpy((char*)buf, "Error Tx\r\n");
} else {

// Read 2 bytes from the temperature register
ret = HAL_I2C_Master_Receive(&hi2c1, TMP102_ADDR, buf, 2, HAL_MAX_DELAY);
if ( ret != HAL_OK ) {
strcpy((char*)buf, "Error Rx\r\n");
} else {

//Combine the bytes
val = ((int16_t)buf0 << 4) | (buf1 >> 4);

// Convert to 2's complement, since temperature can be negative
if ( val > 0x7FF ) {
val |= 0xF000;
}

// Convert to float temperature value (Celsius)
temp_c = val * 0.0625;

// Convert temperature to decimal format
temp_c *= 100;
sprintf((char*)buf,
"%u.%u C\r\n",
((unsigned int)temp_c / 100),
((unsigned int)temp_c % 100));
}
}

// Send out buffer (temperature or error message)
HAL_UART_Transmit(&huart2, buf, strlen((char*)buf), HAL_MAX_DELAY);

// Wait
HAL_Delay(500);

/* USER CODE END WHILE */

/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}

// Rest of auto-generated Cube functions
// ...

 

Let’s take a look at the I2C portion of the code. To begin reading temperature, we first send a write request to the TMP102 with the following HAL API function:

Copy Code
ret = HAL_I2C_Master_Transmit(&hi2c1, TMP102_ADDR, buf, 1, HAL_MAX_DELAY);

 

We pass in a handle to our I2C typedef with &hi2c1 and the address of the TMP102 on the bus. Note that the address should be 0x48 (with A0 tied to ground on the TMP102), but we need to left-shift that byte by 1 bit, as we are using a 7-bit address. We also pass in our buffer, which is simply a uint8_t array, along with the number of bytes we wish to send (1 byte). Because this is a blocking function, we need to tell it how long to wait before giving up. We will use HAL_MAX_DELAY, which comes out to be something like 50 days. Feel free to use your own timeout period here.

The return value, which we store in ret, is a common HAL Status type. If the returned value is not equal to HAL_OK, we transmit an error message to the console. Otherwise, we continue to the read function:

Copy Code
ret = HAL_I2C_Master_Receive(&hi2c1, TMP102_ADDR, buf, 2, HAL_MAX_DELAY);

 

This works similarly to the transmit function. We provide the I2C peripheral handle and the address of the TMP102 on the bus. While we pass in the same buffer, it will be used as an output. When the function returns, if all goes well, the bytes read from the TMP102 will be stored in that buffer. Since we expect 2 bytes from the TMP102 (temperature data is sent as 12 bits), we tell the function that we want to read 2 bytes. Finally, we use the HAL_MAX_DELAY to essentially have no timeout.

Again, we hope to have HAL_OK as our return value. If so, we can expect the buffer, buf, to contain our temperature data. We can then perform some math to transform the 12-bit value into a human readable format, like Celsius. The math for calculating the temperature data can be found in the Digital Temperature Output section of the TMP102 datasheet.

Running and Debugging

Save your code. Click Project > Build Project. The project should compile without any errors. When it’s done, click Run > Debug As > STM32 MCU C/C++ Application

Click OK on the pop-up window asking you to set the debug configurations. The default configurations will work for now. Click Switch when asked about switching to a new perspective. Click the Resume button at the top of the toolbar to begin running code on the Nucleo board.

The installation process for STM32CubeIDE should have installed any necessary serial drivers for the Nucelo boards by default. If not, follow the instructions on this mbed page to install the drivers.

Open up your favorite serial terminal program and connect it to the COM port of your Nucleo board with a baud rate of 115200 (8 data bits, no parity, 1 stop bit). You should see temperature data (in Celsius) being reported twice per second.

Receiving TMP102 temperature data over serial

Try lightly placing your finger on the TMP102 or breathing on it. You should see the reported temperature go up. If you remove the connections to SCL or SDA, you should see error messages being reported.

Error messages from I2C

Resources and Going Further

Try talking to other I2C devices! Additionally, if you take a look at the I2C transmit and receive functions, you will see that they are blocking, which means that the program will not continue until those functions have completed. Take a look at the HAL API documentation for your particular board, and you’ll notice that there are lots of other I2C functions. The functions that end with _IT() rely on hardware interrupts within the STM32, which means you can construct non-blocking versions of our I2C communication. Give it a shot!

Download STM32CubeIDE: https://www.st.com/en/development-tools/stm32cubeide.html

Key Parts and Components

Add all Digi-Key Parts to Cart
  • 497-15881-ND
  • AE9929-ND
  • 1568-1520-ND
  • BKGS-400-ND
  • 1568-1512-ND