I'm currently fleshing out the driver logic for the I2C temperature sensor. My primary focus is on ensuring robust error handling and clear data transfer protocols within the STM32's I2C framework. I'm prioritizing efficient data acquisition and considering potential optimizations for various sensor models. Further refinement aims at minimizing interrupt latency and maximizing code readability.
Selecting Optimal Approach
I've decided to proceed with the HAL driver for the STM32 and chose the LM75/TMP75 style sensor as the base for the I2C temperature sensor implementation. This design choice provides a practical starting point, with considerations for other compatible sensors. The project will now incorporate clear documentation on prerequisites, the sensor's protocol, and step-by-step setup in CubeMX. The approach will include a header file for function prototypes, aiming for broad applicability and configurability.
Composing the I2C Logic
I'm currently focused on the .c file, where the core logic will reside, and have moved on to main.c, focusing on usage examples and practical applications of the functions. Critical aspects include robust error handling, specifically with I2C timeouts. My design incorporates the standard LM75 address and relevant registers, and I'm drafting Sensor_Init and Sensor_Read functions. My refinement involves addressing the existing code's direct approach, aiming for structured implementation.
Addressing Protocol Details
I'm currently addressing specific I2C addressing details for the STM32 HAL. I've realized the need for explicit clarification regarding the 8-bit addressing used by HAL versus the 7-bit addressing often found in datasheets. Furthermore, I've incorporated the 16-bit left-aligned approach for temperature readings, a common strategy for LM75/TMP102-style sensors. This includes necessary bit manipulation and scaling for accurate temperature interpretation. I've decided to proceed with the LM75/TMP102 approach, which provides a good balance between simplicity and demonstration of typical I2C reading.
Integrating Hardware Assumptions
I've finalized the core functions and am currently weaving in hardware assumptions for the TMP102, specifically the I2C address (0x48 << 1), and the temperature register (0x00). I've structured my logic with TMP_Init() and TMP_Read() functions, using the HAL driver for initialization and data transactions, including error handling. I'm focusing on providing clear examples of STM32CubeMX configuration (I2C1, 100kHz). Also, I've incorporated context regarding hardware pull-up resistors. My implementation addresses signed temperature values via casting and provides an example of addressing for these sensors.
Adding Configuration Steps
I'm now detailing the necessary configuration steps, specifically for STM32CubeMX and the HAL library usage. I'm building out tmp102.h, tmp102.c, and a complete main.c implementation to showcase how to use the driver. I've added a visual connection guide and error handling tips, including HAL_OK checks, to ensure robust operation.
To provide a working example, I will write a driver for the TMP102 (or the compatible LM75), which are industry-standard digital temperature sensors.
The focus is on using the STM32 HAL (Hardware Abstraction Layer) library, as this is the standard workflow for STM32 development in STM32CubeIDE.
Prerequisites
Hardware: STM32 MCU, TMP102/LM75 Sensor, 4.7kΩ data line pull-up resistors (usually included on sensor breakout boards).
Software: STM32CubeIDE/CubeMX.
Connections:
VCC -> 3.3V
GND -> GND
SCL -> STM32 SCL Pin (e.g., PB6)
SDA -> STM32 SDA Pin (e.g., PB7)
1. STM32CubeMX Configuration
Before writing code, ensure I2C is enabled in your configuration tool (.ioc file):
Go to Connectivity -> I2C1.
Set I2C to "I2C".
Parameters: Standard Mode (100 kHz) is sufficient.
Generate Code.
2. Driver Header File (tmp102.h)
Create a new header file to define the sensor address and function prototypes.
Note on Addressing: I2C uses 7-bit addresses. The TMP102 defaults to 0x48. The STM32 HAL requires the address to be left-shifted by 1 (bitwise << 1) to make room for the Read/Write bit. So 0x48 becomes 0x90.
c
/*
* tmp102.h
* Simple driver for TMP102 or LM75 Temperature Sensor
*/
#ifndef INC_TMP102_H_
#define INC_TMP102_H_
#include "stm32f4xx_hal.h" // Change this to your family (e.g., stm32f1xx_hal.h, stm32g0xx_hal.h)
// I2C Address (0x48 shifted left by 1)
#define TMP102_ADDR (0x48 << 1)
// Register Addresses
#define TMP102_REG_TEMP 0x00
#define TMP102_REG_CONF 0x01
// Function Prototypes
HAL_StatusTypeDef TMP102_Init(I2C_HandleTypeDef *hi2c);
float TMP102_ReadTemperature(I2C_HandleTypeDef *hi2c);
#endif /* INC_TMP102_H_ */
3. Driver Source File (tmp102.c)
This file contains the logic to communicate with the sensor.
c
/*
* tmp102.c
*/
#include "tmp102.h"
// Timeout duration in milliseconds
#define I2C_TIMEOUT 100
/**
* @brief Checks if the sensor is connected and ready.
* @param hi2c Pointer to a I2C_HandleTypeDef structure.
* @retval HAL status
*/
HAL_StatusTypeDef TMP102_Init(I2C_HandleTypeDef *hi2c)
{
// Check if device is ready (pings the address)
return HAL_I2C_IsDeviceReady(hi2c, TMP102_ADDR, 2, I2C_TIMEOUT);
}
/**
* @brief Reads temperature from the sensor.
* @param hi2c Pointer to a I2C_HandleTypeDef structure.
* @retval Temperature in Celcius (float). Returns -999.0 on error.
*/
float TMP102_ReadTemperature(I2C_HandleTypeDef *hi2c)
{
uint8_t buf[2];
int16_t val;
// 1. Send the Register Pointer (Temperature Register)
// We want to read from register 0x00
buf[0] = TMP102_REG_TEMP;
// Transmit the register address (Write operation)
// Note: If loop reads continuously, you theoretically only need to set the pointer once,
// but setting it every time is safer.
if (HAL_I2C_Master_Transmit(hi2c, TMP102_ADDR, buf, 1, I2C_TIMEOUT) != HAL_OK)
{
return -999.0f; // Error handler
}
// 2. Receive 2 Bytes of Data
if (HAL_I2C_Master_Receive(hi2c, TMP102_ADDR, buf, 2, I2C_TIMEOUT) != HAL_OK)
{
return -999.0f; // Error handler
}
// 3. Process Data
// The TMP102 returns 12-bit data (or 16-bit extended).
// Format: MSB first.
// Combine the two bytes:
// MSB is buf[0], LSB is buf[1].
// Basic LM75/TMP102 Logic:
// The raw data is 12 bits left-aligned in the 16-bit word.
val = ((int16_t)buf[0] << 4) | (buf[1] >> 4);
// Handling negative temperatures (2's complement) is handled by int16_t cast,
// but specific sensors might need sign bit extension if doing bit shifts manually.
// For TMP102 12-bit normal mode:
if (val > 0x7FF) {
val |= 0xF000; // Sign extension for negative numbers
}
// Convert to Float (Resolution is usually 0.0625 C per bit)
return val * 0.0625f;
}
4. Main Implementation (main.c)
In your main.c (generated by CubeMX), you need to include the header and call the functions.
c
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "tmp102.h" // Include your custom driver
#include <stdio.h> // For printf/sprintf if needed
/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c1; // Defined by HAL
UART_HandleTypeDef huart2; // Assuming you want to print to UART
/* Private user code ---------------------------------------------------------*/
int main(void)
{
/* MCU Configuration--------------------------------------------------------*/
HAL_Init();
SystemClock_Config();
// Initialize all configured peripherals
MX_GPIO_Init();
MX_USART2_UART_Init(); // Assume UART for debugging
MX_I2C1_Init(); // Your I2C Init
/* User Code Begin */
// 1. Initialize / Check Sensor
if (TMP102_Init(&hi2c1) == HAL_OK)
{
HAL_UART_Transmit(&huart2, (uint8_t*)"Sensor Found!\r\n", 15, 100);
}
else
{
HAL_UART_Transmit(&huart2, (uint8_t*)"Sensor Error!\r\n", 15, 100);
while(1); // Stop here if hardware fails
}
float temperature;
char msg[32];
while (1)
{
// 2. Read Temperature
temperature = TMP102_ReadTemperature(&hi2c1);
// 3. Debug Output (Print float)
// Note: Ensure float formatting is enabled in your IDE settings
// Or cast to int for simple printing: (int)temperature, (int)((temperature - (int)temperature)*100)
sprintf(msg, "Temp: %.2f C\r\n", temperature);
HAL_UART_Transmit(&huart2, (uint8_t*)msg, strlen(msg), 100);
HAL_Delay(1000); // Read every 1 second
}
/* User Code End */
}
Key Concepts in the Code
HAL_I2C_Master_Transmit:
This tells the sensor which internal register we want to talk to.
In TMP102_ReadTemperature, we transmit 0x00 to set the internal pointer to the Temperature Register.
HAL_I2C_Master_Receive:
This actually reads the data.
Standard temperature sensors usually return 2 bytes.
Bitwise Operations:
((int16_t)buf[0] << 4) | (buf[1] >> 4): I2C sends data as 8-bit packets. We have to stitch them back together into a 16-bit integer.
The specific shifting depends on the sensor datasheet (Left aligned vs Right aligned). The example above is for a standard TMP102 12-bit resolution.
Troubleshooting Common Issues
Hal Returns HAL_BUSY or HAL_ERROR:
Check your pull-up resistors (4.7kΩ from SDA to 3.3V and SCL to 3.3V).
Swap SDA and SCL wires; it happens to the best of us.
Address NACK:
Ensure the address shift << 1 matches the HAL requirement.
Some sensors have an ADD0 pin that changes the address if tied to GND or VCC. Check the datasheet.
Floating Point not printing:
By default, some STM32 linkers disable float printing to save space. If sprintf prints nothing for %f, go to Project Properties > C/C++ Build > Settings > MCU Settings and enable "Use float with printf from newlib-nano".