STM32CubeMX - HTU21D temperature and humidity sensor

preface

High feeling has chased the dawn and clouds, and does not dream with pear flowers———— Su Shi's "moon on the West River: plum blossom"

1, Introduction

HTU21 temperature and humidity sensor is made of high-performance humidity sensing elements based on Humirel in France. HTU21 series modules provide accurate and reliable temperature and humidity measurement data for OEM customer applications. HTU21 not only has diversified output modes and wide working voltage range, but also has high temperature accuracy and humidity accuracy.

HTU21D temperature and humidity sensor can achieve the digital output of temperature and humidity through the interface of a microcontroller and the connection of modules. The resolution of HTU21D can be changed by inputting commands (8/12bit or even 12/14bit RH/T). The sensor can detect the low battery state and output checksum, which helps to improve the reliability of communication. The sensor outputs a calibrated digital signal in standard I2C format.

Supplementary note: OEM is the abbreviation of Original Equipment Manufacturer, which means the manufacturer that usually has abundant and cheap labor force and provides entrusted services for manufacturing and assembling products required by the international market, that is, the agent factory. A modern and popular production mode in which the manufacturer is responsible for production, providing manpower and site, and the purchaser is responsible for sales.

  • Features and applications:

Characteristics of sensorApplication examples
Complete interchangeability without calibration in standard environmentHome application
It is in the state of humidity saturation for a long time and can recover quicklyMedical field
Automatic assembly process production, made of lead-free materials, suitable for reflow solderingprinter
Each sensor is individually marked to trace the source of productionHumidifier
  • Performance specifications:

  • Electrical characteristics and basic performance: (at T = 25 ° C, Vdd = 3.3V)

  • Sensor circuit and pin definitions

    • Circuit diagram: (including pull-up resistor RP and decoupling capacitance between VDD and GND)
    • Pin definition:

Physical drawing:

  • The following more concise temperature and humidity sensor I use, in contrast, removes two NC pins and can be directly connected with STM32 development board;
  • Front view:

2, Pin configuration

These four pins are GND, VCC (+), SCL and SDA respectively. The specific pins have been indicated in the figure of the introduction.

  • VCC: connected to the positive pole of power supply 3.3~5V;
  • GND: grounding;
  • SCL (serial clock input): PB10 (I2C2_SCL)
  • SDA (ship type data port): PB11 (I2C2_SDA)

Wiring list:

Interface of temperature and humidity sensorIO port of STM32Set the working mode of the
VCCVCC(3.3V)-
GNDGND-
SCL (serial clock input)PB10Clock signal line of I2C
SDA (serial data port)PB11I2C data signal line
-PA9TX (USART1 serial port 1 communication)
-PA10Serial port (ART1)
  • Power supply pin (VDD, GND): the power supply range of HTU21 is 1.8VDC - 3.6VDC, and the recommended voltage is 3.0V. A decoupling capacitor of 0.1uF must be connected between power supply (VDD) and ground (VSS), and the position of the capacitor should be as close as possible to the sensor.
  • Serial clock input (SCL): SCL is used for communication synchronization between microprocessor and HTU21D. Since the interface contains fully static logic, there is no minimum SCL frequency.
  • Serial DATA (DATA): the DATA pin is a three state structure, which is used to read sensor DATA. When sending a command to the sensor, the DATA is valid at the rising edge of SCK and must remain stable at SCK high level. DATA changes after the falling edge of SCK. When reading DATA from the sensor, the DATA is valid after the SCK becomes low and maintained to the falling edge of the next SCK. In order to avoid signal conflict, the microprocessor should drive DATA at low level. An external pull-up resistor (e.g. 10k Ω) is required to pull the signal to high level. The pull-up resistor is usually included in the I/O circuit of the microprocessor.

3, "Communication" between STM32 single chip microcomputer and sensor

1. Start the sensor

Power on the sensor. The voltage is the selected VDD power supply voltage (range between 1.8V and 3.6V). After power on, the sensor takes up to 15 milliseconds (at this time, SCL is high level) to reach the idle state, that is, be ready to receive the command sent by the host (MCU) (be ready to communicate with MCU).

2. Start signal

Start transmission and send one bit of DATA, including DATA line. There is a jump to low level during the high level of SCK line.

  • There are three types of signals in the process of I2C bus data transmission:
    • Start signal: when SCL is high level, SDA jumps from high level to low level and starts transmitting data.
    • End signal: when SCL is high level, SDA jumps from low level to high level and ends data transmission.
    • Response signal: the I2C receiving data sends a specific low-level pulse to the I2C sending data after receiving 8bit data, indicating that the data has been received. After sending a signal to the controlled unit, the CPU waits for the controlled unit to send a response signal. After receiving the response signal, the CPU makes a judgment on whether to continue transmitting the signal according to the actual situation. If no response signal is received, it is judged that the controlled unit has failed.
  • Among these signals, the start signal is necessary, and the end signal and response signal can be omitted.

3. Stop signal

When the transmission is terminated and the DATA transmission is stopped, including the DATA line, there is a jump to the high level during the high level of the SCK line.

4. I2C data transmission

If the SCL clock level is low, you can change the level of SDA data line and send SDA data during the rising edge of SCL. When SCL is high, the data on SDA remains stable.

5. HTU21D data measurement

  • Sensor command table:


  • There are two different communication modes between MCU and sensor: host mode and non host mode

    • Host mode: SCL line is blocked (controlled by sensor) during measurement,
    • Non host mode: during the measurement, the SCL line remains open and other communication can be carried out.

In non host mode, MCU needs to query the sensor status. This process is completed by sending a start transmission sequence, followed by the first byte of I2C (1000 0001) as shown in the figure. If the internal processing is completed, after the single chip microcomputer inquires the confirmation signal sent by the sensor, the relevant data can be read through MCU. If the measurement processing is not completed and the sensor has no ACK output, the start transmission sequence must be sent again.

6. HTU21D data reading and conversion

The default resolution set inside the sensor is 12 bits of relative humidity and 14 bits of temperature. The output data of SDA is converted into a two byte packet, with the high byte MSB in the front (left aligned). Each byte is followed by a reply bit. The two status bits, i.e. the last two bits of LSB, must be set to '0' before physical calculation.

4, New project

1. Open STM32CubeMX software and click "new project"

2. Select MCU and package

3. Configure clock



For specific learning, please refer to: Blog website RCC learning

4. Configure debugging mode

5. Serial port (USART1) configuration

6. I2C configuration

7. Generate code

Enter the project name and path. (Note: Chinese is not allowed in the path.)

Select the IDE of the application and the development environment MDK-ARM V5

Each peripheral generates an independent ' c/.h 'document

  • Unchecked: all initialization codes are generated in main c
  • Check: the initialization code is generated in the corresponding peripheral file. For example, the GPIO initialization code is generated in GPIO C.

    Click GENERATE CODE to generate the code

8. Construction works

  • The DeBug mode is selected according to different chips:

4, Write code

In main C file, add the following code:

  • Rewrite fget and fput functions: check the micro Library (this is very important) and add the header file < stdio h>;
/* USER CODE BEGIN Includes */
#include<stdio.h>
/* USER CODE END Includes */
/**
  * Function function: redirect c library function printf to DEBUG_USARTx
  * Input parameters: None
  * Return value: None
  * Description: None
  */
int fputc(int ch, FILE *f)
{
  HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff);
  return ch;
}
 
/**
  * Function function: redirect c library function getchar,scanf to DEBUG_USARTx
  * Input parameters: None
  * Return value: None
  * Description: None
  */
int fgetc(FILE *f)
{
  uint8_t ch = 0;
  HAL_UART_Receive(&huart1, &ch, 1, 0xffff);
  return ch;
}

  • Add code htu21d file pair (. c/.h):
  • htu21d.h:
#ifndef __HTU21D_H_
#define __HTU21D_H_

#include "i2c.h"

//Handle definition
#define HTU21D_I2C hi2c2

//Read write command
#define HTU21D_WRITE_CMD	0x80
#define HTU21D_READ_CMD		0x81

//Sensor command
#define HTU21D_TRIGGER_T_M 						 0xe3 		// Trigger temperature measurement (hold host) 0xe3 = 1110 0011
#define HTU21D_TRIGGER_RH_M 						 0xe5 		// Trigger relative humidity measurement (hold host) 0xe5 = 1110 0101
#define HTU21D_TRIGGER_T_NO_M 					 0xf3 		// Trigger temperature measurement (non holding host) 0xf3 = 1111 0011
#define HTU21D_TRIGGER_RH_NO_M  				     0xf5 		// Trigger relative humidity measurement (non holding host) 0xf5 = 1111 0101 
#define 	 HTU21D_WRITE_USER_REGISTER 		         0xe6 		// Write user register 					  0xe6 = 1110 0110 
#define HTU21D_READ_USER_REGISTER 			 	 0xe7 		// Read user register 					  0xe7 = 1110 0111 
#define HTU21D_SOFT_RESER 						 0xfe 		// Soft reset 						  0xfe = 1111 1110	



//HTU21D value structure
typedef struct{
	float temperature;		//temperature 
	float humidity;			//humidity 
}HTU21D_Value;


/*Reset software*/
void HTU21D_SoftReset(void);
/*Read user register*/
uint8_t HTU21D_ReadUserReg(void);
/*Read temperature and humidity (without waiting for the master chip)*/
float read_temperture(uint8_t cmd);
float read_humidity(uint8_t cmd);


#endif /*__HTU21D_H_*/

  • htu21d.c:
#include "HTU21D.h"

static HTU21D_Value HTU21DValue;

/*External function*/

/*Software reset*/
void HTU21D_SoftReset(void)
{
	HAL_I2C_Master_Transmit(&HTU21D_I2C, HTU21D_WRITE_CMD<<1, (uint8_t *)HTU21D_SOFT_RESER, 1, 100);//Send software reset
}

/*Read user register*/
uint8_t HTU21D_ReadUserReg(void)
{
	uint8_t data=0;
	HAL_I2C_Master_Transmit(&HTU21D_I2C, HTU21D_WRITE_CMD<<1, (uint8_t *)HTU21D_READ_USER_REGISTER, 1, 100);//Send instruction to read user register
	
	HAL_I2C_Master_Receive(&HTU21D_I2C, HTU21D_WRITE_CMD<<1, &data, 1, 100);
	return data;
}

/*Read temperature and humidity*/
float read_temperture(uint8_t cmd)
{
	uint8_t data = cmd;
	uint8_t tempBuff[2];
	uint16_t temp1=0;
	
	HAL_I2C_Master_Transmit(&HTU21D_I2C, HTU21D_WRITE_CMD, &data, 1, 100);
	HAL_I2C_Master_Receive(&HTU21D_I2C, HTU21D_READ_CMD, tempBuff, 2, 100);
	
	temp1 = (uint16_t)tempBuff[0];
	temp1 <<= 8;
	
	temp1 |= tempBuff[1];
	
	HTU21DValue.temperature = -46.85 + 175.72*((float)temp1/(1<<16));		//Data Book temperature conversion formula
	
	return HTU21DValue.temperature;
}

float read_humidity(uint8_t cmd)
{
	uint8_t data = cmd;
	uint8_t humiBuff[2];
	
	uint16_t humi1=0;
	
	HAL_I2C_Master_Transmit(&HTU21D_I2C, HTU21D_WRITE_CMD, &data, 1, 100);
	HAL_I2C_Master_Receive(&HTU21D_I2C, HTU21D_READ_CMD, humiBuff, 2, 100);
	
	humi1 = (uint16_t)humiBuff[0];
	humi1 <<= 8;
	
	humi1 |= humiBuff[1];
	
	HTU21DValue.humidity = -6 + 125*((float)humi1/(1<<16));						//Data Book humidity conversion formula
	
	return HTU21DValue.humidity;
}

  • In the main function main Add code to C:
/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
  float temperture;	//Receiving temperature
  float humidity;//Receiving humidity
  uint8_t cmd;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C2_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
    /* USER CODE BEGIN 3 */
    cmd = HTU21D_ReadUserReg();
    temperture = read_temperture(cmd);
    humidity = read_humidity(cmd);
    
    printf("Read current environment status:\r\n");
    printf("The temperature is:%f centigrade\r\n",temperture);
    printf("Humidity:%f RH\r\n",humidity);
    printf("\n");
    
    HAL_Delay(10000);
  }
  /* USER CODE END 3 */
}

5, Experimental results

Thanks for reading!!!

Tags: Embedded system Single-Chip Microcomputer stm32

Posted by tom92 on Wed, 04 May 2022 11:39:41 +0300