STM32 Chapter 9-IIC Communication Application

STM32 Chapter 9-IIC Communication Application

Speaking of IIC (usually called I2C, in fact, they are all the same) communication is the simplest communication protocol. When learning STM32, the first contact is the serial port USART communication protocol, the next is the IIC communication protocol, and the other is the SPI protocol. We will talk about SPI in the next chapter, and this chapter will talk about IIC. Many modules have used IIC communication, the most common is the 4-pin 0.96 inch OLED display. Of course, when learning STM32, we generally first come into contact with EEPROM through IIC, but in this chapter we only talk about the protocol itself. .

1. Introduction to IIC

The IIC (Inter-Integrated Circuit) bus is a two-wire serial bus developed by PHILIPS, which is used to connect the microcontroller and its peripherals. It is a serial bus composed of data line SDA and clock SCL, which can send and receive data. Two-way transmission is carried out between the CPU and the controlled IC, and between the IC and the IC. The high-speed IIC bus can generally reach more than 400kbps. There are three types of signals in the I2C bus in the process of transmitting data. They are: start signal, end signal and response signal. Start signal: When SCL is high, SDA jumps from high to low and starts to transmit data. End signal: When SCL is high level, SDA jumps from low level to high level, ending the data transmission. Response signal: After receiving the 8bit data, the IC receiving the data sends a specific low-level pulse to the IC sending the 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 the CPU receives the response signal, it determines whether to continue to transmit the signal according to the actual situation. If the response signal is not received, it is determined that the controlled unit is faulty. Among these signals, the start signal is necessary, and the end signal and response signal are not required. IIC uses the SDA signal line to transmit data, and the SCL signal line for data synchronization. The SDA data line transmits one bit of data in each clock cycle of SCL. During transmission, when SCL is high, the data indicated by SDA is valid, that is, when SDA is high at this time, it means data "1", and when it is low, it means data "0". When SCL is low, the data of SDA is invalid. Generally, SDA switches the level at this time to prepare for the next display of data. Each data transmission is in bytes, and the number of bytes transmitted each time is not limited. If we directly control the two GPIO pins of STM32, which are used as SCL and SDA respectively, according to the timing requirements of the above-mentioned signals, directly control the output of the pins like LED lights (if it is receiving data, read the SDA level), Can realize IIC communication. Similarly, if we control the pins according to the requirements of USART, USART communication can also be realized. So as long as you comply with the agreement, it is standard communication. No matter how you implement it, whether it is a controller produced by ST or a memory produced by ATMEL, you can interact according to the communication standard. Because when directly controlling the GPIO pin level to generate the communication sequence, the CPU needs to control the pin state at each moment, so it is called the " software analog protocol " method. In contrast, there is also the " hardware protocol " method. The IIC on-chip peripheral of STM32 is specifically responsible for implementing the IIC communication protocol. As long as the peripheral is configured, it will automatically generate communication signals according to the protocol requirements, send and receive data and cache them, and the CPU only needs to Check the status of the peripheral and access the data register to complete the data transmission and reception. This way of processing the IIC protocol by hardware peripherals reduces the work of the CPU and makes the software design easier.

2. Communication features: serial, synchronous, non-differential, low rate

  • I2C belongs to serial communication , and all data is transmitted serially on the SDA line in units of bits.
  • Synchronous communication means that both parties of communication work under the same clock. Generally, party A of the communication transmits A's own clock to B through a CLK signal line, and B works under the clock transmitted by A. So the distinguishing feature of synchronous communication is: CLK is in the communication line.
  • Non-differential . Because the I2C communication rate is not high, and the communication parties are very close, the level signal communication is used.
  • Low rate . I2C is generally used for communication between two ICs on the same board, and the amount of data used for transmission is not large, so the communication rate itself is very low (generally several hundred KHz, the communication rate of different I2C chips may be different, The specific I2C communication rate allowed by the device you use when programming depends on the maximum rate allowed by the device you are using, and this rate cannot be exceeded)

Outstanding feature 1: master device + slave device (must be clear)

  • In I2C communication, the status of the two communicating parties is not equal, but the master device and the slave device are divided. The communication is initiated by the master device and led by the master device. The slave device passively accepts the communication from the master device according to the I2C protocol and responds in time.

  • Who is the master device and who is the slave device is determined by the communication parties (the I2C protocol is not specified). Generally speaking, a chip can only be the master device, it can only be the slave device, or it can be both the master device and the slave device. Can be used as a slave device (software configuration).

  • Many people think that the microcontroller is the master device and the device is the slave device during communication, which is not rigorous. The STM32 microcontroller can also be used as a slave device, but you haven't seen it before.

Outstanding feature 2: Multiple devices can be hung on a bus (slave device address)

  • I2C communication can be one-to-one (1 master device to 1 slave device) or one-to-many (1 master device to multiple slave devices).
  • The master device is responsible for scheduling the bus and decides which slave device to communicate with at a certain time. Note: At the same time, the I2C bus can only transmit the communication information of a pair of devices, so only one slave device can communicate with the master device at the same time, and the other slave devices are in the "hibernation" state and cannot come out to make trouble, otherwise the communication will be lost. It's messed up.
  • Each I2C slave device has an I2C slave device address in the communication, this device address is the inherent attribute of the slave device itself, and then the master device needs to know the address of the slave device that it will communicate with, and then pass the address in the communication Let s check if it s the slave device you are looking for. ( This address is unique on a circuit board, not the only one in the world )

I2C bus idle state, start bit, end bit

  • There is 1 master device and n (n>=1) slave devices on the I2C bus. There are two states on the I2C bus: idle state (all slave devices are not communicating with the master device, and the bus is idle at this time) and busy state (one slave device is communicating with the master device, and the bus is occupied by this pair at this time, and the other The slave device must rest).
  • The entire communication is divided into one cycle and one cycle, and two adjacent communication cycles are idle. Each communication cycle starts with a start bit, ends with an end bit, and the communication data of this cycle is in the middle.
  • The start bit is not a point in time. The start bit is a period of time. During this period of time, the state of the bus changes as follows: SCL line maintains a high level, while SDA line has a falling edge from high to low.
  • Similar to the start bit, the end bit is also a time period. During this period of time, the state of the bus changes as follows: The SCL line maintains a high level, while the SDA line has a rising edge from low to high.

How to keep in mind the timing of the start signal and end signal of IIC communication? We regard IIC communication as a boat wandering in the water, the surface of the ship as the SDA data line, and the undulations on the water surface as the clock SCK of the IIC communication. Without a water boat, we can t go. Similarly, there is no communication without a clock line. Because SCL maintains a high level, the SDA line has a falling edge starting signal from high to low, so we can use the bow of the ship as the starting signal (imagine a small boat on the lake Row). At the same time, SCL maintains a high level. A rising edge from low to high on the SDA line is a stop signal, so we can regard the stern as a stop signal (is the angle between the stern of the boat and the water surface 45 ?). So if you can't remember the timing of IIC communication, imagine that you are sitting in a small boat, sitting down on the boat, holding a computer and writing the IIC driver .

I2C data transmission format (data bit & ACK)

  • The initiation and termination of each communication cycle is done by the master device. The slave device only passively responds to the master device, and cannot do anything spontaneously.
  • The master device will first send an 8-bit slave device address in each communication cycle ( in fact, only 7 bits of the 8 bits are the slave device address, and 1 bit indicates whether the master device needs to write or read ) to the bus (the master device is It is sent in the form of broadcast, as long as all slave devices on the bus can actually receive this information ). Then every slave device on the bus can receive this address, and after receiving the address, compare it with its own device address to see if it is equal. If they are equal, it means that the main device is talking to me this time. If you don t want to wait, it means that this communication has nothing to do with me, so you don t need to listen to it.
  • After the sender sends a piece of data, the receiver needs to respond with an ACK. The response itself has only 1 bit, which cannot carry valid information, and can only express two meanings (either it means that the data is received, that is, a valid response; or it means that the data is not received, that is an invalid response). The response signal ACK can only be sent by the receiver, because the receiver can only respond after the sender sends data.
  • At a certain communication moment, only one of the master device and the slave device can send (occupying the bus, that is, writing to the bus), and at the rising edge of each clock, prepare the data to be sent, and the sender can respond effectively The signal ACK can only be sent by the receiver, because only after the sender sends data can the receiver respond to a receiving (reading from the bus). If at a certain time both the master and the slave try to write to the bus, it will be over, and the communication will be messed up.

Data transfer protocol on the bus

  • The basic data unit of I2C communication is also in bytes , and the effective data transmitted each time is 1 byte (8 bits).
  • The start bit and the next 8 CLKs are all sent by the master device (the master device controls the bus). At this time, the slave device can only read the bus, and the information sent by the master device to the slave device can be learned by reading the bus; In the 9th cycle, according to the protocol, the slave device needs to send an ACK to the master device, so the master device must release the bus at this time (the master device sets the bus to high level and then does not move, in fact, it is similar to the bus idle state), and the slave device ACK is sent after trying to pull the bus low. If the slave device fails to pull the bus low, or the slave device does not pull the bus low at all, the phenomenon seen by the master device is that the bus remains high in the 9th cycle. This means that I did not receive an ACK for the master device. The master device thinks that the 8 bytes sent to the slave device just now are wrong (reception failed)

2. Software simulation protocol

1. IIC initialization function

Function: configure the clock line and data line of IIC

void IIC_Init ( void ) { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOC, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12|GPIO_Pin_11; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //Push-pull output GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOC, &GPIO_InitStructure); IIC_SCL = 1 ; IIC_SDA = 1 ; } Copy code

Because it is software simulating IIC, we choose the pins of IIC communication relatively freely. For the specific pins used, please refer to the "STM32F1xx Specification", which shall prevail. Here we choose PC11, PC12 as the data and clock pins of IIC. Just set it to push-pull output.

2. Start signal

Function: CPU initiates I2C bus start signal

void IIC_Start ( void ) { IIC_SDA = 1 ; IIC_SCL = 1 ; delay_us( 4 ); IIC_SDA = 0 ; //START: When CLK is high, DATA changes from high to low delay_us( 4 ); IIC_SCL = 0 ; //Clamp the I2C bus and prepare to send or receive data delay_us( 4 ); } Copy code

After the start signal is generated, all slave devices begin to wait for the STM32's next slave address signal. On the IIC bus, the address of each device is unique. When the address broadcast by the host is the same as the address of a certain device, the device is selected, and the unselected device will ignore the subsequent data signal. According to the IIC protocol, this slave address can be 7 or 10 bits. After the address bit, is the selection bit of the transmission direction. When this bit is 0, it means that the subsequent data transmission direction is from the host to the slave, that is, the host writes data to the slave. When this bit is 1, the opposite is true, that is, the master reads the data from the slave.

3. Waiting for the response signal

Function: CPU generates a clock and reads the ACK response signal of the device

//Return value: 1, failed to receive response 0, successful received response u8 IIC_Wait_Ack ( void ) { u8 re; IIC_SDA = 1 ;delay_us( 1 ); //CPU releases the SDA bus IIC_SCL = 1 ;delay_us( 1 ); //CPU drives SCL=1, the device will return an ACK response if (READ_SDA){ //CPU reads SDA Port line status re = 1 ; } else { re = 0 ; } IIC_SCL = 0 ; //clock output 0 return re; } Copy code

This function is used when STM32 is used as the sender to wait and process the response or non-response signal from the receiver, that is, generally call the IIC_SendByte function before calling this function to detect the response. STM32 controls the SDA signal line to output a high-impedance state, releases its control over SDA, and is controlled by the receiver; controls the SCL signal line to switch between high and low levels to generate a clock signal. According to the IIC protocol, if the receiver sets SDA to Low level, it means returning a "response" signal, if SDA remains high, it means returning a "non-response" signal; there is a delay between SCL switching high and low levels to ensure that enough time is given Let the receiver return a response signal, use the macro SDA_READ to read the level of the SDA line after a delay, and assign the value of the re variable according to the level value; the function returns the value of re at the end, and returns 0 when the response is received, and no response is received When it returns 1. When STM32 is used as the data receiver, after calling the IIC_ReadByte function, it needs to return a response or non-response signal to the sender. At this time, the IIC_Ack and IIC_Nack functions can be used for processing. This processing is opposite to the IIC_Wait_Ack function. At this time, the SDA line is also controlled by STM32.

4. Answer the signal

Function: CPU generates an ACK signal

//CPU generates an ACK signal void IIC_Ack ( void ) { IIC_SDA = 0 ; //CPU drive SDA=0 delay_us( 2 ); IIC_SCL = 1 ; //CPU generates a clock delay_us( 2 ); IIC_SCL = 0 ; delay_us( 2 ); IIC_SDA = 1 ; //CPU releases the SDA bus } //CPU generates a NACK signal void IIC_Nack ( void ) { IIC_SDA = 1 (); //CPU drive SDA=1 delay_us( 2 ); IIC_SDA = 1 ; //CPU generates 1 clock delay_us( 2 ); IIC_SCL = 0 ; delay_us( 2 ); } Copy code

Both I2C data and address transmissions have a response. The response includes two types of signals: "acknowledgement (ACK)" and "non-acknowledgement (NACK)". As a data receiver, when the device receives a byte of data or address transmitted by I2C, if it wants the other party to continue sending data, it needs to send an "acknowledge (ACK)" signal to the other party, and the sender will continue to send the next data; If the receiving end wants to end the data transmission, it sends a "NACK" signal to the other party. After receiving the signal, the sender will generate a stop signal to end the signal transmission. The specific flow of the code is: according to whether to return the "response" or "non-response" signal, prepare the level of the SDA line first, set the SDA line to low level in the IIC_Ack function, which means the "acknowledge" signal. The SDA line is set to high level, indicating a "non-response" signal; the SCL line is controlled to switch between high and low levels to generate a clock signal, and a delay is added between the high and low levels of the SCL line to ensure that there is enough time for communication The other party receives the level of the SDA signal line; at the end of the IIC_Ack function, after the response signal has been sent, set the SDA line to high again to release the control of the bus to facilitate subsequent communication.

5. Stop signal

Function: CPU initiates I2C bus stop signal

{ IIC_SDA = 0 ; //STOP: When CLK is high, SDA shows an upward adjustment, indicating that the IIC bus stop signal IIC_SCL = 1 ; delay_us( 4 ); IIC_SDA = 1 ; //Send I2C bus end signal } Copy code

The stop signal can be done directly by looking at the timing diagram. When both SCL and SDA are low, first pull the clock line SCL high, and then pull the data line SDA high, and IIC will end the transmission. The above is the software simulating the IIC protocol. In normal applications, we actually don t need to master these specific codes. We just need to know the process principle of the IIC protocol. Generally speaking, we use codes written by others. We just need to know how to use it. If your code is different from mine, it doesn t matter, as long as it can communicate normally. Of course, if your design has some problems in the process, or the display is not normal, we first consider It's not a problem with the underlying protocol, but other problems with your code.

6.IIC send byte

Function: CPU sends 8bit data to I2C bus device

void IIC_SendByte (u8 Byte) { u8 i; /* Send the high bit 7 of the byte first */ for (i = 0 ; i < 8 ; i++) { if (Byte & 0x80 ) { IIC_SDA = 1 ; } else { IIC_SDA = 0 ; } i2c_Delay(); IIC_SCL = 1 ; delay_us( 2 ); IIC_SCL = 0 ; if (i == 7 ) { IIC_SDA = 1 ; //release the bus } Byte <<= 1 ; /* shift one bit to the left */ delay_us( 2 ); } } Copy code

This function takes its input parameter as the data to be output using the I2C protocol, and the size of the data is one byte. The main body of the function is an 8-times for loop, the body of the loop will send a data bit to the outside when executed once, and the byte of data will be sent just after the end of the loop. The steps are broken down as follows: 1. the program performs an AND operation on the input parameter Byte and 0x80, and judges the logic value of its highest bit. When it is 1, it controls SDA to output high level, and when it is 0, it controls SDA to output low level; then delay, This is to ensure that the output level of the SDA line is stable, and then perform subsequent operations; then control the SCL line to generate high and low level jumps, that is, generate the communication clock of the SCL line in the I2C protocol; there is a gap between the high and low levels of the SCL line Delay. During the delay period, the SCL line maintains a high level. According to the I2C protocol, the data is valid at this time, and the other party of the communication will read the level logic of the SDA line at this time. When the level is high, the bit received is data 1 , Otherwise it is 0; in this way, the execution of the loop body ends, and the Byte is shifted one bit to the left to send the next data in the next loop; for example, the 8 data bits in the Byte are sent after the second loop 8 times. After the bit transmission is completed (the cycle counter i=7 at this time), the SDA line is controlled to output 1 (that is, the high-impedance state), that is, the sender releases the SDA bus and waits for the receiver's response signal.

7.IIC read byte

Function: CPU reads 8bit data from IIC bus device

u8_t IIC_ReadByte ( void ) { u8 i; u8 value; //Read the first bit as data bit7 value = 0 ; for (i = 0 ; i < 8 ; i++) { value <<= 1 ; IIC_SCL = 1 ; delay_us( 2 ); if (DA_READ) { value++; } IIC_SCL = 0 ; delay_us( 2 ); } return value; } Copy code

The IIC_ReadByte function also takes the for loop as the main body. The loop body will be executed 8 times. After the execution is completed, one byte of data will be received. The flow of the loop body receiving data is as follows: 1. use a variable value to temporarily store the data to be received. Before the start of the second cycle, the value of value is shifted to the left by 1 bit to make room for bit0 of the value variable. Bit0 will be used to buffer the newly received data bits, received and shifted bit by bit, and finally spelled out the complete Then control the SCL line to switch between high and low levels, and output the clock used for I2C protocol communication; There is a delay between the high and low level switching of the SCL line, which ensures that enough time is given for the data to be sent The sender sends out a level logic signal through the SDA signal line driven by the SCL clock. After this delay, the STM32 as the data receiving end uses the macro SDA_READ to read the level of the SDA signal line. If the signal line is 1 , Then value++, that is, set its bit0 to 1, otherwise do not operate (so the bit will remain at 0), so that one bit of data is read; then after the SCL line is switched to low level, add a delay, So that the receiving end switches the SDA line to output data as needed; until the end of the loop, the value variable contains 1 byte of data, use return to return it as the function return value;

3. hardware agreement

Relatively speaking, hardware IIC directly uses peripherals to control pins, which can reduce the burden on the CPU. However, certain fixed pins must be used as SCL and SDA when using hardware IIC, and software analog IIC can use any GPIO pin, which is relatively flexible. STM32's IIC peripheral can be used as a communication host or slave, supporting 100Kbit/s and 400Kbit/s rates, supporting 7-bit and 10-bit device addresses, supporting DMA data transmission, and having a data verification function. Its IIC peripherals also support the SMBus2.0 protocol. The SMBus protocol is similar to IIC and is mainly used in battery management of notebook computers. The STM32 chip has multiple IIC peripherals, and their IIC communication signals are led to different GPIO pins, which must be configured to these designated pins when used. For the multiplexing function of GPIO pins, please refer to the "STM32F1xx Specification", Subject to it.

IIC initialization function

void IIC_init ( void ) { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD; //open drain output GPIO_Init(GPIOA, &GPIO_InitStructure); IIC_SCL = 1 ; IIC_SDA = 1 ; //Give a stop signal to reset all devices on the I2C bus to standby mode } Copy code

Because the hardware IIC directly uses peripherals to control the pins, the pins we choose for IIC communication are relatively fixed. For the specific pins used, please refer to the "STM32F1xx Specification", which shall prevail. It can be seen that the two pins PB6 and PB7 can be used as the communication pins of IIC, and PB6 is the SCL clock line, and PB7 is the SDA data line, and is set as an open-drain output. Why is it set to open-drain output here? This is because software is used to simulate the IIC mode, and the open-drain output mode required for the GPIO of the IIC protocol. The open-drain output mode actually outputs a high-impedance state when outputting a high level. When all devices on the IIC bus output a high-impedance state When, it is pulled up to high level by an external pull-up resistor. In addition, when the STM32's GPIO is configured in open-drain output mode, it can still obtain the input level of the external pin by reading the input data register of the GPIO, which means that it also has the function of floating input mode, so in the back There is no need to switch the GPIO mode when controlling the external output level of the SDA line or reading the level signal of the SDA line. In addition, under the IIC protocol, its start signal, waiting response signal, response signal, and stop signal are the same as the functions under the software simulation IIC protocol, so I won't repeat it here. Summary: The IIC communication protocol is very simple. In actual projects, we don't need to master the specific IIC protocol code, as long as we can use it. As the most common and commonly used protocol, we'd better memorize it or understand it. Now IIC communication is no stranger to it!