Embedded system development 14 - using AHT20 sensor to collect temperature and humidity based on I2C protocol

This article mainly introduces the I2C bus communication protocol, and on this basis, uses the STM32F103 to complete the data collection of the AHT20 temperature and humidity sensor based on the I2C protocol, and outputs the collected temperature-humidity value through the serial port.

1. Task requirements

Learn the I2C bus communication protocol, use the STM32F103 to complete the data collection of the AHT20 temperature and humidity sensor based on the I2C protocol, and output the collected temperature-humidity value through the serial port. Specific tasks:
1) Explain what are "software I2C" and "hardware I2C"? (Read Chapter 23 "I2C - Reading and Writing EEPROM" principle chapter of the wildfire supporting textbook)
2) Read the AHT20 data manual and program to realize: collect temperature and humidity data every 2 seconds, and send it to the host computer (win11) through the serial port .

2. I2C bus communication protocol

1. Introduction to I2C

The IIC (Inter-Integrated Circuit) bus is a two-wire serial bus developed by NXP (formerly PHILIPS) for connecting microcontrollers and their peripherals. It is mostly used for master-slave communication between the master controller and slave devices . It is used in small data volume occasions, the transmission distance is short , and there can only be one master at any time.

I2C is a very common bus protocol. I2C is designed by NXP. I2C uses two lines to communicate data between the master controller and the slave . One is SCL (serial clock line) , and the other is SDA (serial data line) . Since the pull-up resistor is not connected, these two pins are in a floating state, and the level of the floating state pin cannot be determined . Therefore, these two data lines need to be connected with pull-up resistors , generally 4.7K, and both SCL and SDA are at high level when the bus is idle .
insert image description here

The I2C bus performs bidirectional transmission between the CPU and the controlled device, and between the controlled device and the controlled device . The speed of the I2C bus can reach 100Kb/S in standard mode and 400Kb/S in fast mode . The I2C bus works according to a certain protocol. I2C supports multiple slaves , that is, multiple I2C slave devices can be connected to one I2C controller . These different I2C slave devices have different device addresses, so the I2C master The controller can access the specified I2C device through the device address of the I2C device, and one I2C bus can connect multiple I2C devices. Note that I2C was invented to communicate with low-speed devices, so the transmission rate of I2C is not as good as SPI .
insert image description here

2. Characteristics of I2C bus

I²C Features:

  • Only one data line SDA and one clock line SCL are needed , **SDA (serial data line)** and SCL (serial clock line) are both bidirectional
    I/O lines SCL (Serial Clock): serial clock line , to transmit CLK signal, generally the master device provides
    SDA (Serial Data) to the slave device : serial data line, to transmit communication data

  • Multi-master bus , any device can be used as both a master and a slave, but there can only be one master at a time , and each device connected to the bus can be addressed by software through a unique address; it can be detected through an external connection , which is convenient System troubleshooting and debugging

  • The number of ICs connected to the same bus is only limited by the maximum capacitance of the bus. The serial 8-bit bidirectional data transmission bit rate can reach 100Kbit/s in standard mode, 400Kbit/s in fast mode, and up to 100Kbit/s in high-speed mode. 3.4Mbit/s

  • The current consumed on the bus is very small, therefore, the number of devices extended on the bus is mainly determined by the capacitive load, anti-high noise interference, adding a bus driver can increase the bus capacitance by 10 times, and the transmission distance can reach 15m; compatible with different voltage levels devices that operate over a wide temperature range

  • The interface circuit is an open- drain output , which needs to be connected to the power supply VCC through a pull-up resistor . When the bus is idle , both lines are at high level , and the external devices connected to the bus are all CMOS device output stages, which are also open-drain circuits. In order to avoid bus signal confusion, it is required that each device connected to the output of the bus must be an open-drain (OD) output or an open- collector (OC) output

  • There is no strict baud rate requirement , such as using RS232, the master device generates the bus clock, generates the start signal and stop signal

  • IIC is half-duplex , not full-duplex, and can only communicate in one direction at the same time

transfer speed:

  • Standard Mode: Standard Mode = 100 Kbps
  • Fast Mode: Fast Mode = 400 Kbps
  • High speed mode: High speed mode = 3.4 Mbps
  • Ultra fast mode: Ultra fast mode = 5 Mbps

Maximum number of master devices: unlimited

The maximum number of slaves: theoretically 127

3. I2C physical layer

The physical connection of the I2C bus is very simple, consisting of SDA (serial data line) , SCL (serial clock line) and pull-up resistors . The communication principle is to generate the signals required by the I2C bus protocol for data transmission by controlling the high and low level timing of the SCL and SDA lines . When the bus is idle , SCL and SDA are pulled high by the pull-up resistor Rp , keeping high .

The I2C communication mode is half-duplex , and there is only one SDA line, which can only communicate in one direction at the same time . 485 is also half-duplex, and SPI and uart communication are full-duplex .
insert image description here

The concept of master and slave:

The master is responsible for the task coordination and distribution of the entire system. The slave usually completes certain tasks by receiving instructions from the master. The master and the slave are connected through the bus for data communication.
The one that issues the main command is called the master, and the one that accepts the command is called the slave

4. I2C protocol layer

There are three types of signals in the process of transmitting data on the I2C bus, they are: start signal, end signal and response signal .

When the start signal SCL is high level, SDA jumps from high level to low level, and starts to transmit data.
When the end signal SCL is high level, SDA jumps from low level to high level, and the data transmission ends.
Response signal After receiving 8bit data, the IC that receives data sends a specific low-level pulse to the IC that sends data, indicating that the data has been received. After the CPU sends a signal to the controlled unit, it waits for the controlled unit to send a response signal. After receiving the response signal, the CPU makes a judgment on whether to continue to transmit the signal according to the actual situation. If no response signal is received, it is judged that the controlled unit is faulty.

Among these signals, the start signal is required , and the end signal and the response signal are optional.

5. I2C bus timing diagram

insert image description here

Start bit:
I2C start communication sign, the host tells the slave to start communication through this sign, when SCL is high level, SDA shows the start bit when the next edge appears
insert image description here

Stop bit:
The sign of the end of I2C communication, when SCL is high and SDA has a rising edge, it indicates the stop bit
insert image description here

Data transmission:
I2C data bus transmission should ensure that when SCL is high level, SDA data is stable , so the data change on SDA can only be when SCL is low level
insert image description here

Address frame/read/write bit/ACK bit:
insert image description here

Address frame: This is an 8-bit data, of which the upper 7 bits are the device address, and the last bit is the read and write bit. If it is 1, it means this is a read operation, and if it is 0, it means this is a write operation.

Read/write bit: 0: low level, the master device writes data to the slave device, 1: high level, the slave device reads data

ACK: Each frame of the message has an acknowledgment bit. If the device receives the address frame or data frame, it will return an ACK to the sending device

Idle state:
When the two signal lines of the data line SDA and the clock line SCL of the IIC bus are at high level at the same time, it is defined as the idle state of the bus. At this time, the output stage field effect transistors of each device are in the cut-off state , that is, the bus is released, and the level is pulled up by the pull-up resistors of the two signal lines.

Response signal:
Every time the transmitter sends a byte (8 bits), it releases the data line during clock pulse 9, and the receiver feeds back a response signal.

When the response signal is low level , it is defined as an effective response bit (ACK, referred to as response bit) , indicating that the receiver has successfully received the byte ; when the response signal is high level, it is specified as a non- acknowledgment bit (NACK) , Generally indicates that the receiver did not succeed in receiving the byte

insert image description here

The receiver pulls the data line SDA low during the low level before the ninth clock pulse, and ensures that it is a stable low level during the high level of the clock, and sends an ACK signal. If the receiver is the host side, After it receives the last byte, it sends a NACK signal to notify the controlled transmitter to end data transmission, and releases the data line SDA so that the host can send a stop signal P

Supplement:
The non-response signal may be sent by the master or the slave.
There are several possibilities:
1. There is no slave device with the address specified by the master on the I2C bus.
2. The slave is performing some operations and is in a busy state. Not ready to communicate with the host
3. Some control commands sent by the host, the slave does not support
4. When the host receives data from the slave, the host generates a non-response signal to notify the slave that the data transmission is over and do not send any more data

6. Data transmission

Data transmission:
The host writes to the slave timing sequence, the red part represents the master transmission, and the blue part represents the slave transmission. A means answer, NA means non-answer (high level). S means start signal, P means stop signal
insert image description here
insert image description here

  • 1. Start signal: Before SCL switches from high level to low level, the master device switches SDA from high level to low level, and the start signal and stop signal are always generated by the control of the master device
  • 2. The master device sends the 7-bit or 10-bit address of the slave device to communicate with each slave device, and decides which I2C device to access by sending the specific device address. This is an 8-bit data, of which the high 8 The bit is the device address, the last bit is the read and write bit, 1 means read operation, 0 means write operation
  • 3. Each slave device will compare the address sent by the master device with its own address. If the address matches, the slave device will pull SDA low to return the ACK response signal. When the address does not match, the slave device will pull SDA High, when the slave device does not pull SDA low, the Master will be regarded as timeout, and the data transmission will be abandoned, and "Stop" will be sent
  • 4. Resend the start signal
  • 5. The host sends the register address of the cluster machine to be written
  • 6. Slave sends ACK signal
  • 7. Send the data frame to be written into the register. After transmitting each data frame, that is, 8-bit data, the master pulls SDA high, waits for the slave to pull SDA low, and then returns ACK to confirm that the frame has been successfully received
  • 8. End signal: The master device switches SCL to high level, and then switches SDA to high level, thus sending a stop signal to the slave device

Data reception:
insert image description here
insert image description here
Receiving data is the process of reading timing, which is mainly divided into four major steps: 1. Sending the device address; 2. Sending the register value to be read; 3. Resending the device address; 4. I2C output from the device register value to read

  • 1. The host sends a start signal
  • 2. The host sends the address of the slave device to be read and written
  • 3. Read and write control bit, because it is to send data to the I2C slave device, so it is a write signal
  • 4. The slave sends an ACK response signal
  • 5. Resend the start signal
  • 6. The host sends the address of the register to be read
  • 7. The ACK response signal sent by the slave
  • 8. Resend START signal
  • 9. Resend the I2C slave device address to be read
  • 10. Read and write control bit, here is the read signal, indicating that the next step is to read data from the I2C slave device
  • 11. The ACK response signal sent by the slave
  • 12. Read data from I2C device
  • 13. When the last 8 bits of data are read, the host should set SDA to 1, and the host sends a NO ACK signal, indicating that the reading is complete, and the slave does not need to send an ACK signal again
  • 14. The host sends a STOP signal to stop I2C communication

Note:
SCL is always controlled by the host , and SDA follows the direction of data transmission. When reading data, the slave controls SDA, and when writing data, the host controls SDA. After the 8-bit data is transmitted, the SDA control right of the acknowledge bit or the negative acknowledge bit is opposite to that of the data bit.

7. Software I2C and hardware I2C

I2C is divided into software I2C and hardware I2C

Software IIC software I2C communication refers to the I2C simulated by the two I/O ports of the microcontroller, using software to control the pin state to simulate the I2C communication waveform, and the software to simulate the working mode of the register.

Directly use the CPU core to control the GPIO output high and low levels according to the requirements of the I2C protocol, thereby simulating I2C.
Use: When controlling the start signal of I2C, control the GPIO pin as the SCL line to output high level, and then control the GPIO pin as the SDA line to complete the switching from high level to low level during this period. Finally, control the SCL line to switch to low level, so that a standard I2C start signal is output.

Hardware I2C is a hardware circuit. The hardware I2C corresponds to the I2C peripheral on the chip, and has a corresponding I2C driver circuit. The I2C pins used are also dedicated. The hardware (firmware) I2C directly calls the internal registers for configuration.

Direct use of the hardware I2C peripheral in the STM32 chip.
Use: As long as the corresponding registers are configured, the peripheral will generate the timing of the standard serial port protocol. After initializing the I2C peripherals, you only need to set a certain register bit to 1, and then the peripherals will control the corresponding SCL and SDA lines to automatically generate the I2C start signal, without the need for the core to directly control the pin level.

The efficiency of hardware I2C is much higher than that of software , and software I2C has a more flexible interface because it is not limited by pins.

3. Implementation process

1. Task requirements

Read the AHT20 data manual, and program to realize: collect temperature and humidity data every 2 seconds, and send it to the host computer (win11) through the serial port.

2. Preparation

It is recommended to modify and add code based on the sample code provided by punctual atom or wildfire.

You can go to the official website to view and download related AHT20 materials: http://www.aosong.com/class-36.html

3. Core code

The process of using the AHT20 chip read_AHT20_onceFunction :

void  read_AHT20_once(void)
{
    
    
	delay_ms(1);

	reset_AHT20();//重置AHT20芯片
	delay_ms(1);

	init_AHT20();//初始化AHT20芯片
	delay_ms(1);

	startMeasure_AHT20();//开始测试AHT20芯片
	delay_ms(1);

	read_AHT20();//读取AHT20采集的到的数据
	delay_ms(1);
}

AHT20 chip read data read_AHT20function :

void read_AHT20(void)
{
    
    
	uint8_t   i;
	for(i=0; i<6; i++)
	{
    
    
		readByte[i]=0;
	}
	I2C_Start();//I2C启动

	I2C_WriteByte(0x71);//I2C写数据
	ack_status = Receive_ACK();//收到的应答信息
	readByte[0]= I2C_ReadByte();//I2C读取数据
	Send_ACK();//发送应答信息

	readByte[1]= I2C_ReadByte();
	Send_ACK();

	readByte[2]= I2C_ReadByte();
	Send_ACK();

	readByte[3]= I2C_ReadByte();
	Send_ACK();

	readByte[4]= I2C_ReadByte();
	Send_ACK();

	readByte[5]= I2C_ReadByte();
	SendNot_Ack();
	//Send_ACK();

	I2C_Stop();//I2C停止函数
	//判断读取到的第一个字节是不是0x08,0x08是该芯片读取流程中规定的,如果读取过程没有问题,就对读到的数据进行相应的处理
	if( (readByte[0] & 0x68) == 0x08 )
	{
    
    
		H1 = readByte[1];
		H1 = (H1<<8) | readByte[2];
		H1 = (H1<<8) | readByte[3];
		H1 = H1>>4;

		H1 = (H1*1000)/1024/1024;

		T1 = readByte[3];
		T1 = T1 & 0x0000000F;
		T1 = (T1<<8) | readByte[4];
		T1 = (T1<<8) | readByte[5];

		T1 = (T1*2000)/1024/1024 - 500;

		AHT20_OutData[0] = (H1>>8) & 0x000000FF;
		AHT20_OutData[1] = H1 & 0x000000FF;

		AHT20_OutData[2] = (T1>>8) & 0x000000FF;
		AHT20_OutData[3] = T1 & 0x000000FF;
	}
	else
	{
    
    
		AHT20_OutData[0] = 0xFF;
		AHT20_OutData[1] = 0xFF;

		AHT20_OutData[2] = 0xFF;
		AHT20_OutData[3] = 0xFF;
		printf("测量失败!!!");
	}
	printf("\r\n");
	//根据AHT20芯片中,温度和湿度的计算公式,得到最终的结果,通过串口显示
	printf("当前温度为:%d%d.%d\n",T1/100,(T1/10)%10,T1%10);
	printf("当前湿度为:%d%d.%d",H1/100,(H1/10)%10,H1%10);
	printf("\r\n");
}

4. Project overview

insert image description here

5. Project address

I have packaged and uploaded the project to the gitee warehouse, the address is as follows:

Using AHT20 sensor to realize temperature acquisition based on I2C bus protocol

4. Compile and burn

1. Hardware connection

Connection method of communication module and power supply module:

USB to TTL STM32F103C8T6
GND G
3V3 3V3
RXD PA9
TXD PA10

Note that BOOT0 on the core board is set to 1, and BOOT1 is set to 0

insert image description here
insert image description here

AHT20 sensor module connection method:

STM32F103C8T6 AHT20 sensor
3.3V Pin 1 (VDD)
PB7 Pin 2 (SDA)
GND Pin 3 (GND)
PB6 Pin 4 (SCL)

insert image description here
insert image description here

2. Compile

(1) Click Options for Target... , check Create HEX File under Output
insert image description here

(2) Check Use Simulator under Debug , change the input box under Dialog DLL to DARMSTM.DLL , and change the Parameter input box to -pSTM32F103C8
insert image description here

(3) Choose to use the V5 compiler in Target
insert image description here

(4) Click Rebuild to compile
insert image description here

3. Burning

Open the FlyMcu Burning Assistant, select the HEX file just generated , and click Start Programming to burn
insert image description here

4. Operation effect

Use the SSCOM serial port debugging assistant to observe the serial port output, and find that the collected temperature can be displayed normally. I put the AHT20 sensor on the cooling vent of the computer, and found that the measured temperature and humidity have changed.

Using AH20 temperature and humidity sensor to collect temperature and humidity based on I2C protocol

insert image description here

V. Summary

Through this experiment, I have a basic understanding of the I2C bus communication protocol. And on this basis, I realized the data acquisition of AHT20 temperature and humidity sensor based on I2C protocol using STM32F103C8T6, and output the collected temperature-humidity value through the serial port.

This experiment not only deepened my understanding of I2C bus protocol, but also deepened my understanding of serial communication related knowledge, and also learned the use of AHT20 temperature and humidity sensor.

During the completion of this experiment, many problems were encountered. At the beginning, I originally planned to use the template I created at the beginning, but halfway through, I found that some necessary files were missing, such as the bsp_i2c.c file ; in addition, when the code started running, the serial port read Temperature and Humidity are always 0.0 . Finally, it was found that because the sensor pins were very thin, they could not be fixed well, so in order to make the temperature sensor more firmly connected to the Dupont wire, some tin was added to the four pins of the sensor, so that the temperature sensor was indeed fixed. It was fixed, but it caused poor contact, and the problem was successfully solved by changing a sensor later.

Finally, only in the process of hands-on practice can you discover the limitations of the knowledge you have mastered, and you can discover the problems and solutions that are easy to encounter during the implementation process, so as to improve your ability to solve problems.


Reference list:
1. I2C bus communication protocol and practical operation stm32 realizes temperature and humidity (AHT20) acquisition through I2C
2. Detailed explanation of I2C bus protocol (features, communication process, typical I2C timing)
3. Introduction to i2c bus protocol
4. Understand I2C in one article letter of agreement

Guess you like

Origin blog.csdn.net/qq_52068373/article/details/127629640