Temperature sensor not working
To get my first sensor project done and after selecting my board, I enabled I2C1 which triggered pins PB6 and PB7 as shown below:
Then used code below (in main.c) with the purpose that the LED is on when the temperature is higher than 40 degrees and off otherwise.
#include "main.h"
extern I2C_HandleTypeDef hi2c1; // I2C handle from CubeMX
#define HTU21D_ADDR (0x40 << 1) // 7-bit address shifted for HAL
#define TRIGGER_TEMP_MEASURE_HOLD 0xE3
I2C_HandleTypeDef hi2c1;
UART_HandleTypeDef huart2;
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_I2C1_Init(void);
float HTU21D_ReadTemperature(void)
{
uint8_t cmd = TRIGGER_TEMP_MEASURE_HOLD;
uint8_t data[2];
// Send temperature measurement command
HAL_I2C_Master_Transmit(&hi2c1, HTU21D_ADDR, &cmd, 1, HAL_MAX_DELAY);
// Receive 2 bytes (temperature)
HAL_I2C_Master_Receive(&hi2c1, HTU21D_ADDR, data, 2, HAL_MAX_DELAY);
// Combine and mask status bits
uint16_t rawTemp = (data[0] << 8) | data[1];
rawTemp &= 0xFFFC;
// Convert to Celsius
float temp = -46.85 + 175.72 * ((float)rawTemp / 65536.0);
return temp;
}
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART2_UART_Init();
MX_I2C1_Init();
while (1)
{
if ( HTU21D_ReadTemperature() > 40.0f)
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET); // LED ON
else
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET); // LED OFF
HAL_Delay(1000); // check every 1s
}
}The wiring is also this way:
PB6 -> Sensor's SCL (there's also a 220 Ohm resister between SCL and MCU 3.3V)
PB7 -> Sensor's SDL (there's also another 220 Ohm resister between SDL and MCU 3.3V)
sensor's GND -> MCU GND
sensor's VCC -> MCU 3.3V
The issue is that the LED is on while the room's temperature is obviously less than 40 degrees!
Any idea where the problem is, please?
