aymen ammari
DIIDevHeads IoT Integration Server
•Created by Boss lady on 7/2/2024 in #firmware-and-baremetal
How can I read data from an I2C temperature sensor (TMP102) using an STM32 microcontroller?
Try this code instead
#include "stm32f1xx_hal.h"
I2C_HandleTypeDef hi2c1;
#define TMP102_ADDR (0x48 << 1) // TMP102 default address (0x48) shifted for HAL functions
#define TEMP_REG 0x00 // Temperature register address
uint8_t buffer[2];
void TMP102_Init(void) {
hi2c1.Instance = I2C1;
hi2c1.Init.ClockSpeed = 100000;
hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c1.Init.OwnAddress1 = 0;
hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c1) != HAL_OK) {
Error_Handler();
}
}
float TMP102_ReadTemperature(void) {
uint8_t reg = TEMP_REG;
float temperature = 0.0;
if (HAL_I2C_Master_Transmit(&hi2c1, TMP102_ADDR, ®, 1, HAL_MAX_DELAY) != HAL_OK) {
Error_Handler();
}
if (HAL_I2C_Master_Receive(&hi2c1, TMP102_ADDR, buffer, 2, HAL_MAX_DELAY) != HAL_OK) {
Error_Handler();
}
int16_t rawTemp = (buffer[0] << 8) | buffer[1];
rawTemp >>= 4;
temperature = rawTemp * 0.0625;
return temperature;
}
void Error_Handler(void) {
while(1);
}
int main(void) {
HAL_Init();
TMP102_Init();
while (1) {
float temperature = TMP102_ReadTemperature();
HAL_Delay(1000);
}
}
6 replies