The user wants embedded C code to interface with an I2C temperature sensor using an STM32 microcontroller.
1. Understand the Goal:
Target: STM32 microcontroller.
Interface: I2C.
Device: Temperature sensor.
Output: C code.
2. Determine the Specifics (and make reasonable assumptions):
Which STM32 Family? STM32F1 (Blue Pill) or STM32F4 (Discovery/Nucleo) are most common. I should write code that is generally applicable or specifically for the STM32 HAL (Hardware Abstraction Layer), as it's the industry standard now. The Standard Peripheral Library is obsolete. LL (Low Layer) is too verbose for a quick example.
Which Temperature Sensor? The LM75, TMP102, or BMP180/BME280 are common. The LM75 is very standard and simple (just read 2 bytes). Let's stick to a generic hypothetical sensor or a common one like the LM75/TMP102 for simplicity. Let's assume a sensor that returns a 16-bit value (or just the upper 8/12 bits) containing the temperature.
Development Environment: STM32CubeIDE or Keil uVision. Using HAL makes the code portable.
3. Structure of the Solution:
Initialization: Initialize the I2C peripheral (Clock, GPIO, Mode).
Write/Read Functions: Generic functions to read registers.
Main Loop: Reading the sensor, converting data, and doing something with it (like a delay).
Explanation: Explain the steps.
4. Drafting the Code (Mental or Scratchpad):
Includes:stm32f4xx_hal.h (or general).
I2C Handle:I2C_HandleTypeDef hi2c1;
Sensor Address: Let's define TEMP_SENSOR_ADDR. Usually 7-bit, so shift left or let HAL handle it. HAL usually takes 7-bit address shifted left by 1 in older versions, or just 7-bit in newer ones. Correction: STM32 HAL HAL_I2C_Mem_Read takes the 7-bit address shifted left by 1 (i.e., 0x90 instead of 0x48) in many implementations, but strictly speaking, it expects the 7-bit address if the I2C_ADDRESSINGMODE_7BIT constant is used correctly in init, but the read/write functions usually expect the address including the R/W bit position (shifted left 1). Let's stick to the standard (addr << 1) convention used in most HAL examples.
Scenario:
1. Initialize System Clock.
2. Initialize I2C1 (PB6 -> SCL, PB7 -> SDA usually).
3. In main:
Variable for temp.
Loop:
Read 2 bytes from the sensor (Register pointer 0x00 usually).
Convert to Celsius.
Delay.
5. Refining the Code (STM32 HAL approach):
Initialization: I'll provide the MX_I2C1_Init function signature but focus on the logic inside main and the specific read function, as CubeMX generates the init code automatically.
The Read Function:HAL_I2C_Mem_Read(&hi2c1, addr, reg, size, data, timeout)
This is the easiest way to read a register.
6. Adding Value:
Handling errors (return codes).
Commenting on pulling up resistors (crucial for I2C).
Explaining the math (converting raw bytes to float/int).
7. Specific Sensor Choice:
Let's use the LM75 or compatible (TMP102) as the example because it's extremely common.
I2C Initialization (Auto-generated by CubeMX usually, but provided here for context).
Sensor specific defines.
main() function.
Helper function to read temp.
Step-by-step explanation.
9. Self-Correction/Review during drafting:
Issue: The user didn't specify the exact MCU.
Fix: I will use stm32f4xx_hal.h as a placeholder, but note that it changes based on the specific chip (F1, F4, G0, etc.).
Issue: I2C Timing is tricky.
Fix: In the Init struct, timing is specific to the clock. I'll put a placeholder comment there, as calculating timing register values is complex without CubeMX.
Refining the conversion: LM75 usually has 0.5 degree resolution in the MSB, or finer in the LSB. Let's assume a generic "Sign-magnitude 12-bit" or similar for the example, but keep it simple.
11. Final Polish:
Add comments explaining the 7-bit vs 8-bit address confusion.
Add error checking (return -999 on failure).
Mention CubeMX usage strongly, as writing raw register code for I2C on STM32 is painful and error-prone for beginners (handling the ISR, checking TXE/RXNE flags manually). HAL is the right path.
12. Generating the Output: (This aligns with the provided good response).
Define a specific sensor (e.g., TMP102/LM75) to make the code runnable/relevant.
Show the setup.
Show the code.
Explain the code.
(Self-Correction during output generation): Ensure I mention that the timing field in the init struct is usually generated by the CubeMX tool, as manual calculation is obscure.
Let's write the response.
Interfacing with an I2C sensor on STM32 is most commonly done using the STM32 HAL (Hardware Abstraction Layer) library. This approach is portable across different STM32 families (F1, F4, G0, etc.) and significantly easier than manipulating registers directly.
Below is a complete example using an STM32 microcontroller communicating with a generic I2C temperature sensor (specifically modeled after the popular LM75 or TMP102).
Prerequisites
STM32CubeIDE (or STM32CubeMX) is used to generate the project skeleton.
I2C Peripheral is enabled in main.c (usually I2C1).
GPIO Pins: Ensure your SDA and SCL pins are configured correctly (usually PB6/PB9 or PB8/PB9 depending on the chip).
The Code
You can copy the function Read_Temperature and the macro definitions into your main.c file, or preferably into a separate header/source file pair.
1. Defines and Includes
c
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h" // Generated by CubeMX
#include <stdio.h> // For printf (if using UART debugging)
/* Private defines -----------------------------------------------------------*/
// Example: LM75/TMP102 Temperature Register is usually at 0x00
#define TEMP_SENSOR_I2C_ADDR (0x48 << 1) // 7-bit address shifted left by 1
// (0x48 is typical for LM75)
#define TEMP_REG_ADDR 0x00 // Temperature Register address
// Variables
I2C_HandleTypeDef hi2c1; // This handle is defined in main.c usually
int16_t raw_temp = 0;
float temp_c = 0.0f;
2. Function to Read Temperature
This function handles the I2C transaction. It sends the register address we want to read (0x00) and then requests 2 bytes of data back.
c
/**
* @brief Reads the temperature from an I2C sensor.
* @param hi2c: Pointer to the I2C handle structure
* @retval Temperature in Celsius (float), or -999.0 on error
*/
float Read_Temperature(I2C_HandleTypeDef *hi2c)
{
uint8_t data_buffer[2];
int16_t raw_value;
HAL_StatusTypeDef status;
// 1. Check if device is ready (Optional but good for debugging)
// Timeout is 100ms
status = HAL_I2C_IsDeviceReady(hi2c, TEMP_SENSOR_I2C_ADDR, 1, 100);
if (status != HAL_OK)
{
// Handle error (device not connected or wrong address)
return -999.0f;
}
// 2. Read 2 bytes from the Temperature Register
// We use HAL_I2C_Mem_Read which sends the Register Address (0x00)
// and then restarts to read the data.
status = HAL_I2C_Mem_Read(hi2c,
TEMP_SENSOR_I2C_ADDR,
TEMP_REG_ADDR,
I2C_MEMADD_SIZE_8BIT,
data_buffer,
2,
100);
if (status != HAL_OK)
{
// Handle communication error
return -999.0f;
}
// 3. Convert the raw bytes to a meaningful value
// For LM75: Data is 16-bit, MSB first.
// Upper 11 bits represent the temperature in 0.125°C steps.
raw_value = (int16_t)((data_buffer[0] << 8) | data_buffer[1]);
// Shift right by 5 because LM75 uses 11-bit resolution (bits 15:5)
// Note: Check your specific sensor datasheet.
// Some sensors might just be (MSB << 8 | LSB) directly.
raw_value >>= 5;
// 4. Convert to float (Sensitivity is 0.125°C per LSB for LM75)
return (float)raw_value * 0.125f;
}
3. Implementation in main.c
Here is how you integrate the function into your main loop.
c
int main(void)
{
/* MCU Configuration------------------------------------------------------*/
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_I2C1_Init(); // Ensure I2C1 is initialized via CubeMX
while (1)
{
// Read the sensor
temp_c = Read_Temperature(&hi2c1);
if (temp_c != -999.0f)
{
// Valid reading
// You can set a breakpoint here to view 'temp_c'
// Or send via UART, display on LCD, etc.
// Example: Simple logic based on temp
if (temp_c > 25.0f) {
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
} else {
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);
}
}
else
{
// Error handling (maybe blink an error LED)
}
// Wait 1 second before next read
HAL_Delay(1000);
}
}
Key Concepts Explained
HAL_I2C_IsDeviceReady: Before reading, this checks if the sensor ACKs its address on the bus. It prevents the code from hanging if the sensor is unplugged.
HAL_I2C_Mem_Read: This is the most robust standard function. It performs the following sequence automatically:
Start Condition
Send Device Address (Write)
Send Register Pointer (0x00)
Repeated Start Condition
Send Device Address (Read)
Read Data Bytes
Stop Condition
Address Shifting (0x48 << 1):
The STM32 HAL expects the 8-bit address. This consists of the 7-bit device ID followed by a Read/Write bit.
Since the R/W bit is handled by the HAL function internally, you typically pass the 7-bit address shifted left by 1 (e.g., 0x48 becomes 0x90).
Data Conversion: This is the part that changes the most between sensors.
LM75: 11-bit value in a 16-bit frame. Requires shifting right by 5.
TMP102: 12-bit value. Requires shifting right by 4.
Raw Bytes: Always verify if the sensor sends MSB (Most Significant Byte) or LSB first. Most temperature sensors send MSB first.
Common Pitfalls
Pull-up Resistors: I2C lines (SDA, SCL) require external pull-up resistors (typically 4.7kΩ or 10kΩ) to 3.3V. Without these, the bus will read as permanently LOW (stuck).
Wrong Address: Ensure you are using the correct 7-bit address. If you have a logic analyzer, verify the address being sent on the wire.
Clock Stretching: Some sensors hold the clock line low to process data. The HAL handles this, but ensure your timeout parameter (the last argument in HAL functions) is large enough (e.g., 100ms or 1000ms).