Data collection of AHT20 temperature and humidity sensor based on I2C protocol

Data collection of AHT20 temperature and humidity sensor based on I2C protocol

  • 1. Basic introduction
    • 1. What is “software I2C” and “hardware I2C”
    • 2.AHT20 temperature and humidity sensor
  • 2. Project establishment
  • 3. Code part
  • 4. Results display and summary

1. Basic introduction

1. What is “software I2C” and “hardware I2C”

Software and protocol layers, hardware is the line
(1) Physical layer of I2C
Only two bus lines are required, one is the serial data line SDA and the other is the serial clock line SCL. (I2C is half-duplex, not full-duplex);
Each device connected to the bus can communicate with other devices through a unique address. The master/slave role and address are configurable. The master can act as a master transmitter and a master receiver;
I2C is a true multi-master bus (and this SPI needs to determine the host before each communication. I2C can change the host during the communication process). If two or more masters request the bus at the same time, collision detection and arbitration can prevent bus data from being corrupted.
The transmission rate can reach 100kb/s in standard mode and 400kb/s in fast mode.
The number of ICs connected to the bus is limited only by the bus’s maximum load capacitance of 400pF.

(2) I2C protocol layer
a) Data validity
The data on the SDA line must remain stable during the high period of the clock, and the data line can only change when the clock SCL is low.
b) Start and end signals
Start condition: When SCL is high level, the transition from high to low on the SDA line is defined as the start signal;
End signal: When SCL is high, the transition from low to high on the SDA line is defined as a stop signal;
Note: The start signal and the stop signal are both sent by the host. If connected to the hardware interface of the I2C bus, the start and stop signals can be easily detected.
The bus is considered busy after a start condition and idle after a stop condition.
c) Reply
Whenever the master sends a byte of data to the slave, the master always needs to wait for a response signal from the slave to confirm whether the slave has successfully received the data. The clock required by the slave to respond to the master is still provided by the master. . The response appears in the clock cycle immediately following each time the host completes the transmission of 8 data bits. A low level of 0 indicates a response, and a 1 indicates a non-response.
d) Data frame format
The data signals transmitted on the I2C bus are broad, including both address signals and real data signals. After the start signal, a slave address (7 bits) must be transmitted. The 8th bit is the data transmission direction (R/T). Use “0” to indicate that the master sends data (T), and use “1” to indicate the host. Receive data (R). Each data transfer is always ended by the host generating a termination signal. However, if the master wishes to continue occupying the bus for new data transmission, it can immediately send a start signal to address another slave without generating a termination signal.

2.AHT20 temperature and humidity sensor

Getting Started with Temperature and Humidity (AHT20) Sensor

Introduction
DHT20 is a new upgraded product of DHT11, equipped with a dedicated ASIC sensor chip, a high-performance semiconductor silicon-based capacitive humidity sensor and a standard on-chip temperature sensor, and uses the standard I2C data output signal format. Its performance has been greatly improved and exceeds the reliability levels of the previous generation sensor (DHT11). The new generation of upgraded products has been improved to make its performance more stable in high temperature and high humidity environments; at the same time, the product’s accuracy, response time, and measurement range have been greatly improved. Every sensor is rigorously calibrated and tested before leaving the factory to ensure and meet customers’ large-scale applications.

Fully calibrated

Digital output, IIC interface

Excellent long-term stability

Quick response and strong anti-interference ability

Wide voltage support 2.2-5.5 VDC

Sensor performance
Relative humidity
Humidity characteristic table:

Typical error and maximum error of relative humidity at 25℃:

temperature
Temperature characteristics table:

Temperature typical error and maximum error:

Electrical characteristics
Electrical characteristics table:

Interface definition

Power supply pin VDD GND:
The power supply range of DHT20 is 2.2-5.5 V, VDD is connected to the voltage input, and GND is connected to ground.

Serial clock SCL:
SCL is used for communication synchronization between the microprocessor and the DHT20. Since the interface contains completely static logic, there is no minimum SCL frequency

Serial data SDA:
The SDA pin is used for sensor data input and output. When sending a command to the sensor, SDA is active on the rising edge of the serial clock (SCL) and must remain stable while SCL is high. After the falling edge of SCL, the SDA value can be changed. To ensure communication security, the valid time of SDA should be extended to TSU and THO before the rising edge of SCL and after the falling edge of SCL, respectively. When reading data from the sensor, SDA is valid (TV) after SCL goes low and remains active until the next falling edge of SCL

Application circuit wiring diagram:

2. Project establishment

1. Configure the clock


2. Set DEBUG

3. Configure IC2 and add I2C1_RX, IC21_TX in the ADD below

4. Configure USART, add RX, TX in the ADD below

5. The last step to create the file

6. The above is the configuration of this project.

3. Code part

main.c function part

/* USER CODE BEGIN Header */
/**
  *************************************************** ****************************
  * @file: main.c
  * @brief: Main program body
  *************************************************** ****************************
  * @attention
  *
  * Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  *************************************************** ****************************
  */
/* USER CODE END Header */
/* Includes ----------------------------------------------- ------------------*/
#include "main.h"
#include "dma.h"
#include "i2c.h"
#include "usart.h"
#include "gpio.h"

/* Private includes -------------------------------------------------- ----------*/
/* USER CODE BEGIN Includes */
#include<stdio.h>
#include "AHT20-21_DEMO_V1_3.h"
/* USER CODE END Includes */

/* Private typedef ----------------------------------------------- -------------*/
/* USER CODE BEGIN PTD */
int fputc(int ch,FILE *f)
{<!-- -->
    HAL_UART_Transmit( & amp;huart1,(uint8_t *) & amp;ch,1,0xFFFF);
//Wait for sending to end
while(__HAL_UART_GET_FLAG( & amp;huart1,UART_FLAG_TC)!=SET){<!-- -->
}

    return ch;
}
/* USER CODE END PTD */

/* Private define -------------------------------------------------- ---------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro ----------------------------------------------- ---------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables -------------------------------------------------- -----------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes ------------------------------------------------ --*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/*Private user code------------------------------------------------ ----------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief The application entry point.
  * @retval int
  */
int main(void)
{<!-- -->
  /* USER CODE BEGIN 1 */
uint32_t CT_data[2]={<!-- -->0,0};
volatile int c1,t1;
Delay_1ms(500);
  /* 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_USART1_UART_Init();
  MX_DMA_Init();
  MX_I2C1_Init();
  MX_USART1_UART_Init();
\t
  /* USER CODE BEGIN 2 */
  AHT20_Init();
Delay_1ms(500);

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {<!-- -->
    /* USER CODE END WHILE */
AHT20_Read_CTdata(CT_data); //Read the temperature and humidity data of AHT20 directly without CRC check. It is recommended to read it every more than 1S.
AHT20_Read_CTdata_crc(CT_data); //After crc verification, read the temperature and humidity data of AHT20
\t

c1 = CT_data[0]*1000/1024/1024; //Calculate the humidity value c1 (enlarged 10 times)
t1 = CT_data[1]*2000/1024/1024-500;//Calculate the temperature value t1 (enlarged 10 times)
printf("Detecting");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
printf("\r\\
");
HAL_Delay(1000);
printf("Temperature:%d%d.%d",t1/100,(t1/10) ,t1 );
printf("Humidity:%d%d.%d",c1/100,(c1/10),c1);
printf("\r\\
");
printf("wait");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
HAL_Delay(100);
printf(".");
printf("\r\\
");
HAL_Delay(1000);
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{<!-- -->
  RCC_OscInitTypeDef RCC_OscInitStruct = {<!-- -->0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {<!-- -->0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig( & amp;RCC_OscInitStruct) != HAL_OK)
  {<!-- -->
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig( & amp;RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {<!-- -->
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{<!-- -->
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {<!-- -->
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef USE_FULL_ASSERT
/**
  * @brief Reports the name of the source file and the source line number
  * where the assert_param error has occurred.
  * @param file: pointer to the source file name
  * @param line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{<!-- -->
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\\
", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

AHT20-21_DEMO_V1_3.h part

#ifndef _AHT20_DEMO_
#define _AHT20_DEMO_

#include "main.h"

void Delay_N10us(uint32_t t);//Delay function
void SensorDelay_us(uint32_t t);//Delay function
void Delay_4us(void); //Delay function
void Delay_5us(void); //Delay function
void Delay_1ms(uint32_t t);
void AHT20_Clock_Init(void); //Delay function
void SDA_Pin_Output_High(void); //Configure PB15 as output and set it to high level, PB15 serves as the SDA of I2C
void SDA_Pin_Output_Low(void); //Configure P15 as output and set to low level
void SDA_Pin_IN_FLOATING(void); //SDA is configured as floating input
void SCL_Pin_Output_High(void); //SCL outputs high level, P14 is used as I2C SCL
void SCL_Pin_Output_Low(void); //SCL output low level
void Init_I2C_Sensor_Port(void); //Initialize the I2C interface, the output is high level
void I2C_Start(void); //I2C host sends START signal
void AHT20_WR_Byte(uint8_t Byte); //Write a byte to AHT20
uint8_t AHT20_RD_Byte(void);//Read a byte from AHT20
uint8_t Receive_ACK(void); //See if AHT20 replies ACK
void Send_ACK(void); //The host replies with ACK signal
void Send_NOT_ACK(void); //The host does not reply ACK
void Stop_I2C(void); //End of a protocol
uint8_t AHT20_Read_Status(void);//Read the status register of AHT20
uint8_t AHT20_Read_Cal_Enable(void); //Check whether the cal enable bit is enabled
void AHT20_SendAC(void); //Send AC command to AHT20
uint8_t Calc_CRC8(uint8_t *message,uint8_t Num);
void AHT20_Read_CTdata(uint32_t *ct); //No CRC check, directly read the temperature and humidity data of AHT20
void AHT20_Read_CTdata_crc(uint32_t *ct); //After CRC verification, read the temperature and humidity data of AHT20
void AHT20_Init(void); //Initialize AHT20
void JH_Reset_REG(uint8_t addr);///Reset register
void AHT20_Start_Init(void);///Power-on initialization and enter the normal measurement state
#endif

AHT20-21_DEMO_V1_3.c

/************************************************/
/*@Copyright: Guangzhou Aosong Electronics Co., Ltd. */
/*@Author: Temperature and Humidity Sensor Division */
/*@Version: V1.2 */
/************************************************/
//#include "main.h"
#include "AHT20-21_DEMO_V1_3.h"
#include "gpio.h"
#include "i2c.h"


void Delay_N10us(uint32_t t)//delay function
{<!-- -->
  uint32_t k;

   while(t--)
  {<!-- -->
    for (k = 0; k < 2; k + + );//110
  }
}

void SensorDelay_us(uint32_t t)//delay function
{<!-- -->
\t\t
for(t = t-2; t>0; t--)
{<!-- -->
Delay_N10us(1);
}
}

void Delay_4us(void) //Delay function
{<!-- -->
Delay_N10us(1);
Delay_N10us(1);
Delay_N10us(1);
Delay_N10us(1);
}
void Delay_5us(void) //Delay function
{<!-- -->
Delay_N10us(1);
Delay_N10us(1);
Delay_N10us(1);
Delay_N10us(1);
Delay_N10us(1);

}

void Delay_1ms(uint32_t t) //Delay function
{<!-- -->
   while(t--)
  {<!-- -->
    SensorDelay_us(1000);//Delay 1ms
  }
}


//void AHT20_Clock_Init(void) //Delay function
//{<!-- -->
// RCC_APB2PeriphClockCmd(CC_APB2Periph_GPIOB,ENABLE);
//}

void SDA_Pin_Output_High(void) //Configure PB7 as output and set to high level, PB7 serves as I2C SDA
{<!-- -->
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;//Push-pull output
GPIO_InitStruct.Pin = GPIO_PIN_7;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOB, & amp; GPIO_InitStruct);
HAL_GPIO_WritePin(GPIOB,GPIO_PIN_7,GPIO_PIN_SET);
}

void SDA_Pin_Output_Low(void) //Configure P7 as output and set to low level
{<!-- -->
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;//Push-pull output
GPIO_InitStruct.Pin = GPIO_PIN_7;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOB, & amp; GPIO_InitStruct);
HAL_GPIO_WritePin(GPIOB,GPIO_PIN_7,GPIO_PIN_RESET);
}

void SDA_Pin_IN_FLOATING(void) //SDA is configured as floating input
{<!-- -->
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;//Float
GPIO_InitStruct.Pin = GPIO_PIN_7;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init( GPIOB, & amp;GPIO_InitStruct);
}


void SCL_Pin_Output_High(void) //SCL outputs high level, P14 is used as I2C SCL
{<!-- -->
HAL_GPIO_WritePin(GPIOB,GPIO_PIN_6,GPIO_PIN_SET);
}

void SCL_Pin_Output_Low(void) //SCL output low level
{<!-- -->
HAL_GPIO_WritePin(GPIOB,GPIO_PIN_6,GPIO_PIN_RESET);
}

void Init_I2C_Sensor_Port(void) //Initialize the I2C interface, the output is high level
{<!-- -->
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;//Push-pull output
GPIO_InitStruct.Pin = GPIO_PIN_7;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOB, & amp; GPIO_InitStruct);
HAL_GPIO_WritePin(GPIOB,GPIO_PIN_15,GPIO_PIN_SET);

\t
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;//Push-pull output
GPIO_InitStruct.Pin = GPIO_PIN_6;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOB, & amp; GPIO_InitStruct);
HAL_GPIO_WritePin(GPIOB,GPIO_PIN_15,GPIO_PIN_SET);
\t
}
void I2C_Start(void) //I2C host sends START signal
{<!-- -->
SDA_Pin_Output_High();
SensorDelay_us(8);
SCL_Pin_Output_High();
SensorDelay_us(8);
SDA_Pin_Output_Low();
SensorDelay_us(8);
SCL_Pin_Output_Low();
SensorDelay_us(8);
}


void AHT20_WR_Byte(uint8_t Byte) //Write a byte to AHT20
{<!-- -->
uint8_t Data,N,i;
Data=Byte;
i = 0x80;
for(N=0;N<8;N + + )
{<!-- -->
SCL_Pin_Output_Low();
Delay_4us();
if(i&Data)
{<!-- -->
SDA_Pin_Output_High();
}
else
{<!-- -->
SDA_Pin_Output_Low();
}
\t\t\t
    SCL_Pin_Output_High();
Delay_4us();
Data <<= 1;
\t\t 
}
SCL_Pin_Output_Low();
SensorDelay_us(8);
SDA_Pin_IN_FLOATING();
SensorDelay_us(8);
}


uint8_t AHT20_RD_Byte(void)//Read a byte from AHT20
{<!-- -->
uint8_t Byte,i,a;
Byte = 0;
SCL_Pin_Output_Low();
\t
SDA_Pin_IN_FLOATING();
SensorDelay_us(8);
\t
for(i=0;i<8;i + + )
{<!-- -->
    SCL_Pin_Output_High();
\t\t
Delay_5us();
a=0;
\t\t
//if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_15)) a=1;
if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_7)) a=1;
Byte = (Byte<<1)|a;
\t\t
//SCL_Pin_Output_Low();
HAL_GPIO_WritePin(GPIOB,GPIO_PIN_6,GPIO_PIN_RESET);
Delay_5us();
}
  SDA_Pin_IN_FLOATING();
SensorDelay_us(8);
return Byte;
}


uint8_t Receive_ACK(void) //See if AHT20 replies ACK
{<!-- -->
uint16_t CNT;
CNT = 0;
SCL_Pin_Output_Low();
SDA_Pin_IN_FLOATING();
SensorDelay_us(8);
SCL_Pin_Output_High();
SensorDelay_us(8);
while((HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_7)) & amp; & amp; CNT < 100)
CNT + + ;
if(CNT == 100)
{<!-- -->
return 0;
}
 SCL_Pin_Output_Low();
SensorDelay_us(8);
return 1;
}

void Send_ACK(void) //The host replies with ACK signal
{<!-- -->
SCL_Pin_Output_Low();
SensorDelay_us(8);
SDA_Pin_Output_Low();
SensorDelay_us(8);
SCL_Pin_Output_High();
SensorDelay_us(8);
SCL_Pin_Output_Low();
SensorDelay_us(8);
SDA_Pin_IN_FLOATING();
SensorDelay_us(8);
}

void Send_NOT_ACK(void) //The host does not reply ACK
{<!-- -->
SCL_Pin_Output_Low();
SensorDelay_us(8);
SDA_Pin_Output_High();
SensorDelay_us(8);
SCL_Pin_Output_High();
SensorDelay_us(8);
SCL_Pin_Output_Low();
SensorDelay_us(8);
    SDA_Pin_Output_Low();
SensorDelay_us(8);
}

void Stop_I2C(void) //End of a protocol
{<!-- -->
SDA_Pin_Output_Low();
SensorDelay_us(8);
SCL_Pin_Output_High();
SensorDelay_us(8);
SDA_Pin_Output_High();
SensorDelay_us(8);
}

uint8_t AHT20_Read_Status(void)//Read the status register of AHT20
{<!-- -->

uint8_t Byte_first;
I2C_Start();
AHT20_WR_Byte(0x71);
Receive_ACK();
Byte_first = AHT20_RD_Byte();
Send_NOT_ACK();
Stop_I2C();
return Byte_first;
}

uint8_t AHT20_Read_Cal_Enable(void) //Check whether the cal enable bit is enabled
{<!-- -->
uint8_t val = 0;//ret = 0,
  val = AHT20_Read_Status();
if((val & amp; 0x68)==0x08)
return 1;
   else return 0;
 }

void AHT20_SendAC(void) //Send AC command to AHT20
{<!-- -->

I2C_Start();
AHT20_WR_Byte(0x70);
Receive_ACK();
AHT20_WR_Byte(0xac);//0xAC collection command
Receive_ACK();
AHT20_WR_Byte(0x33);
Receive_ACK();
AHT20_WR_Byte(0x00);
Receive_ACK();
Stop_I2C();

}

//CRC check type: CRC8/MAXIM
//Polynomial: X8 + X5 + X4 + 1
//Poly: 0011 0001 0x31
//Put the high bit at the back and it becomes 1000 1100 0x8c
//C actual code:
uint8_t Calc_CRC8(uint8_t *message,uint8_t Num)
{<!-- -->
uint8_t i;
uint8_t byte;
uint8_t crc=0xFF;
  for(byte=0; byte<Num; byte + + )
  {<!-- -->
    crc^=(message[byte]);
    for(i=8;i>0;--i)
    {<!-- -->
      if(crc & amp;0x80) crc=(crc<<1)^0x31;
      else crc=(crc<<1);
    }
  }
        return crc;
}

void AHT20_Read_CTdata(uint32_t *ct) //No CRC check, directly read the temperature and humidity data of AHT20
{<!-- -->
volatile uint8_t Byte_1th=0;
volatile uint8_t Byte_2th=0;
volatile uint8_t Byte_3th=0;
volatile uint8_t Byte_4th=0;
volatile uint8_t Byte_5th=0;
volatile uint8_t Byte_6th=0;
uint32_t RetuData = 0;
uint16_t cnt = 0;
AHT20_SendAC();//Send AC command to AHT10
Delay_1ms(80);//The delay is about 80ms
    cnt = 0;
while(((AHT20_Read_Status() & amp;0x80)==0x80))//Until the status bit[7] is 0, it means the idle state, if it is 1, it means the busy state
{<!-- -->
SensorDelay_us(1508);
if(cnt + + >=100)
{<!-- -->
break;
}
}
I2C_Start();
AHT20_WR_Byte(0x71);
Receive_ACK();
Byte_1th = AHT20_RD_Byte();//Status word, the status is 0x98, which means busy state, bit[7] is 1; the status is 0x1C, or 0x0C, or 0x08, which means idle state, bit[7] is 0
Send_ACK();
Byte_2th = AHT20_RD_Byte();//Humidity
Send_ACK();
Byte_3th = AHT20_RD_Byte();//Humidity
Send_ACK();
Byte_4th = AHT20_RD_Byte();//humidity/temperature
Send_ACK();
Byte_5th = AHT20_RD_Byte();//Temperature
Send_ACK();
Byte_6th = AHT20_RD_Byte();//Temperature
Send_NOT_ACK();
Stop_I2C();

RetuData = (RetuData|Byte_2th)<<8;
RetuData = (RetuData|Byte_3th)<<8;
RetuData = (RetuData|Byte_4th);
RetuData =RetuData >>4;
ct[0] = RetuData;//Humidity
RetuData = 0;
RetuData = (RetuData|Byte_4th)<<8;
RetuData = (RetuData|Byte_5th)<<8;
RetuData = (RetuData|Byte_6th);
RetuData = RetuData &0xfffff;
ct[1] =RetuData; //Temperature

}


void AHT20_Read_CTdata_crc(uint32_t *ct) //After CRC verification, read the temperature and humidity data of AHT20
{<!-- -->
volatile uint8_t Byte_1th=0;
volatile uint8_t Byte_2th=0;
volatile uint8_t Byte_3th=0;
volatile uint8_t Byte_4th=0;
volatile uint8_t Byte_5th=0;
volatile uint8_t Byte_6th=0;
volatile uint8_t Byte_7th=0;
uint32_t RetuData = 0;
uint16_t cnt = 0;
// uint8_t CRCDATA=0;
uint8_t CTDATA[6]={<!-- -->0};//For CRC transfer array
\t
AHT20_SendAC();//Send AC command to AHT10
Delay_1ms(80);//The delay is about 80ms
    cnt = 0;
while(((AHT20_Read_Status() & amp;0x80)==0x80))//Until the status bit[7] is 0, it means the idle state, if it is 1, it means the busy state
{<!-- -->
SensorDelay_us(1508);
if(cnt + + >=100)
{<!-- -->
break;
}
}
\t
I2C_Start();

AHT20_WR_Byte(0x71);
Receive_ACK();
CTDATA[0]=Byte_1th = AHT20_RD_Byte();//Status word, the status is 0x98, which means busy state, bit[7] is 1; the status is 0x1C, or 0x0C, or 0x08, which means idle state, bit[ 7] is 0
Send_ACK();
CTDATA[1]=Byte_2th = AHT20_RD_Byte();//Humidity
Send_ACK();
CTDATA[2]=Byte_3th = AHT20_RD_Byte();//Humidity
Send_ACK();
CTDATA[3]=Byte_4th = AHT20_RD_Byte();//humidity/temperature
Send_ACK();
CTDATA[4]=Byte_5th = AHT20_RD_Byte();//Temperature
Send_ACK();
CTDATA[5]=Byte_6th = AHT20_RD_Byte();//Temperature
Send_ACK();
Byte_7th = AHT20_RD_Byte();//CRC data
Send_NOT_ACK(); //Note: NAK is sent at the end
Stop_I2C();
\t
if(Calc_CRC8(CTDATA,6)==Byte_7th)
{<!-- -->
RetuData = (RetuData|Byte_2th)<<8;
RetuData = (RetuData|Byte_3th)<<8;
RetuData = (RetuData|Byte_4th);
RetuData =RetuData >>4;
ct[0] = RetuData;//Humidity
RetuData = 0;
RetuData = (RetuData|Byte_4th)<<8;
RetuData = (RetuData|Byte_5th)<<8;
RetuData = (RetuData|Byte_6th);
RetuData = RetuData &0xfffff;
ct[1] =RetuData; //Temperature
\t\t
}
else
{<!-- -->
ct[0]=0x00;
ct[1]=0x00;//Verification error return value, customers can change it according to their needs
}//CRC data
}


void AHT20_Init(void) //Initialize AHT20
{<!-- -->
Init_I2C_Sensor_Port();
I2C_Start();
AHT20_WR_Byte(0x70);
Receive_ACK();
AHT20_WR_Byte(0xa8);//0xA8 enters NOR working mode
Receive_ACK();
AHT20_WR_Byte(0x00);
Receive_ACK();
AHT20_WR_Byte(0x00);
Receive_ACK();
Stop_I2C();

Delay_1ms(10);//Delay about 10ms

I2C_Start();
AHT20_WR_Byte(0x70);
Receive_ACK();
AHT20_WR_Byte(0xbe);//0xBE initialization command, the initialization command of AHT20 is 0xBE, the initialization command of AHT10 is 0xE1
Receive_ACK();
AHT20_WR_Byte(0x08);//Relevant register bit[3] is set to 1, which is the calibration output
Receive_ACK();
AHT20_WR_Byte(0x00);
Receive_ACK();
Stop_I2C();
Delay_1ms(10);//Delay about 10ms
}
void JH_Reset_REG(uint8_t addr)
{<!-- -->
\t
uint8_t Byte_first,Byte_second,Byte_third;
I2C_Start();
AHT20_WR_Byte(0x70);//originally 0x70
Receive_ACK();
AHT20_WR_Byte(addr);
Receive_ACK();
AHT20_WR_Byte(0x00);
Receive_ACK();
AHT20_WR_Byte(0x00);
Receive_ACK();
Stop_I2C();

Delay_1ms(5);//The delay is about 5ms
I2C_Start();
AHT20_WR_Byte(0x71);//
Receive_ACK();
Byte_first = AHT20_RD_Byte();
Send_ACK();
Byte_second = AHT20_RD_Byte();
Send_ACK();
Byte_third = AHT20_RD_Byte();
Send_NOT_ACK();
Stop_I2C();
\t
  Delay_1ms(10);//Delay about 10ms
I2C_Start();
AHT20_WR_Byte(0x70);///
Receive_ACK();
AHT20_WR_Byte(0xB0|addr);//Register command
Receive_ACK();
AHT20_WR_Byte(Byte_second);
Receive_ACK();
AHT20_WR_Byte(Byte_third);
Receive_ACK();
Stop_I2C();
\t
Byte_second=0x00;
Byte_third =0x00;
}

void AHT20_Start_Init(void)
{<!-- -->
JH_Reset_REG(0x1b);
JH_Reset_REG(0x1c);
JH_Reset_REG(0x1e);
}

4. Results display and summary

This experiment is mainly to learn the I2C bus communication protocol, use STM32F103 to complete the data collection of the AHT20 temperature and humidity sensor based on the I2C protocol, collect temperature and humidity data every 2 seconds, and output the collected temperature-humidity value through the serial port and send Go to the host computer.
One of the problems I encountered at the beginning was that after creating a new file, I did not add the path of the newly added file, which resulted in constant errors. At the same time, when writing the function for reading data from the AHT20 chip, the code must be written according to the I2C communication protocol. The function for sending the response must not be forgotten to be written. Then there was some problem with the code section of the temperature sensor. I found a new file online and added it to solve the problem.
Through the study of this experiment, I have a deeper understanding of I2C communication, which will give me a certain foundation for programming sensors using the I2C communication protocol in the future, and I have gained a lot.