How can I read data from an I2C temperature sensor (TMP102) using an STM32 microcontroller?

Good day guys, how can I read data from an I2C temperature sensor (TMP102) using an STM32 microcontroller? I am encountering the error Failed to read from the I2C bus: Remote I/O error despite confirming that the sensor is powered and the I2C connections are correctly set up. Here is my current code snippet, which attempts to read 10 bytes of data from the sensor:
char buffer[10];
if (read(file, buffer, 10) != 10) {
perror("Failed to read from the I2C bus");
}
char buffer[10];
if (read(file, buffer, 10) != 10) {
perror("Failed to read from the I2C bus");
}
@Middleware & OS @Helper
Solution:
Try this code instead #include "stm32f1xx_hal.h" ...
Jump to solution
4 Replies
Solution
aymen ammari
aymen ammari5mo ago
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, &reg, 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); } }
Boss lady
Boss lady5mo ago
It worked @aymen ammari , can u tell me what I was doing wrong, just in case of next time
ZacckOsiemo
ZacckOsiemo5mo ago
How did you even know she was on an f1
aymen ammari
aymen ammari5mo ago
It's one of these 1. I2C Address: Ensure it’s left-shifted by 1. 2. Initialization: Proper I2C initialization is crucial. 3. Communication Sequence: Write to the pointer register before reading data.
Want results from more Discord servers?
Add your server