When it comes to IIC(usually called I2C, but it’s all the same) communication, it’s the simplest communication protocol. When learning STM32, the first contact is the serial port USART communication protocol, followed by the IIC communication protocol and the SPI protocol, which we will talk about in the next chapter, this chapter will talk about IIC. Many modules have used IIC communication, the most common is the 4-pin 0.96 inch OLED display screen, of course, in the study of STM32, we generally first contact is to communicate with EEPROM through IIC, but this chapter we only talk about the protocol itself.
I. Introduction to IIC
IIC(Inter-Integrated Circuit) bus is a two-wire serial bus developed by PHILIPS, which is used to connect microcontrollers and their peripherals. It is a serial bus composed of data line SDA and clock SCL, which can send and receive data. Bidirectional transmission between CPU and controlled IC, BETWEEN IC and IC, high-speed IIC bus can generally reach more than 400KBps. I2C bus has three types of signals in the process of data transmission, they are: start signal, end signal and response signal. Start signal: WHEN SCL is at high level, SDA jumps from high level to low level and starts to transmit data. End signal: WHEN SCL is at high level, SDA jumps from low level to high level to end data transmission. Acknowledgement signal: The IC receiving data sends a specific low level pulse to the IC sending data after receiving 8 bits of 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 decides 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. In these signals, the start signal is required, the end signal and the response signal can be discarded.IIC uses SDA signal line for data transmission and SCL signal line for data synchronization. The SDA data line transmits one bit of data per clock cycle of the SCL. During transmission, the data represented by SDA is valid when SCL is at high level, that is, SDA at this time represents data “1” when SCL is at high level and data “0” when SCL is at low level. When SCL is low, SDA data is invalid. Generally, SDA switches level at this time to prepare for the next data presentation. Each data transfer is in bytes, and there is no limit on the number of bytes transferred each time. 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 signal, and directly control the output of the pin like an LED lamp (read the SDA level when receiving data), IIC communication can be achieved. Similarly, if we control the pins according to the requirements of USART, we can also achieve USART communication. So as long as the protocol is followed, it is standard communication, no matter how you implement it, whether the CONTROLLER produced by ST or memory produced by ATMEL, can interact according to the communication standard. Since the pin state of each moment needs to be controlled by CPU when the GPIO pin level is directly controlled to generate communication sequence, it is called”Software simulation protocol“Way. In contrast, there is”Hardware agreement“Mode, STM32’s IIC on chip peripherals are specifically responsible for the implementation of IIC communication protocol, as long as the configuration of the peripherals, it will automatically generate communication signals according to the protocol requirements, send and receive data and cache, as long as the CPU detects the status of the peripherals and access to the data register, can complete data transceiver. This approach of handling the IIC protocol by hardware peripherals relieves CPU work and makes software design easier.
2. Communication features: serial, synchronous, non-differential, low speed
- I2C belongs to serial communication. All data is transmitted in bits on the SDA line.
- Synchronous communication means that both parties work under the same clock. Generally, party A transmits its own clock to PARTY B through A CLK signal line, and Party B works under the clock transmitted by Party A. So the salient feature of synchronous communication is CLK in the communication line.
- The difference. Because I2C communication rate is not high, and the communication between the two sides is very close, level signal is used for communication.
- Low rate. I2C is commonly used in the same board of communication between the two IC, and used to transmit data volume is not large, so the communication rate is very low (typically hundreds of KHz, different I2C chip communication rate may be different, specific to see what they use when programming device allows the highest rate of I2C communication, cannot exceed the rate)
Outstanding Feature 1: Master + Slave (must be clear)
-
In I2C communication, the status of the communication parties is not equal, but the master device and the slave device. The communication is initiated and dominated by the master device. The slave device passively receives the communication from the master device in accordance with the I2C protocol and responds in time.
-
Who is the master device and who is the slave device are determined by the communication parties (I2C protocol does not specify). Generally speaking, a chip can only be the master device, or the slave device, or both (software configuration).
-
There are a lot of people think that in communication MCU is the main device, the device is from the device, this is not rigorous. STM32 microcontroller can also be used as a slave device, but you have not seen it.
Outstanding Feature 2: Multiple devices can be hung on a bus (from 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, deciding which slave device to communicate with at any given time. Note: at the same time, the I2C bus can only transmit the communication information of one 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 state of “hibernation” and cannot come out to make trouble, otherwise the communication will be chaotic.
- Each I2C slave device has an I2C slave device address in communication, which is an inherent attribute of the device itself. Then, during communication, the master device needs to know the address of the slave device that it is going to communicate with, and then identifies whether it is the slave device that it is looking for through the address. (This address is unique on a circuit board, not globally)
Bus idle state, start bit, end bit of I2C
- The I2C bus has one master device and N (n>=1) slave devices. There are two states on the I2C bus; Idle (none of the slave devices is communicating with the master device, the bus is idle) and busy (one of the slave devices is communicating with the master device, the bus is occupied by this pair, and the other slave devices must be idle).
- The whole communication is divided into one cycle and one cycle. The two adjacent communication cycles are idle states. Each communication period starts with a start bit and ends with an end bit. In the middle is the communication data of the current period.
- The starting bit is not a time point, but a time period during which the bus state changes as follows: SCL line maintains high level, while SDA line has a falling edge from high to low.
- Like the start bit, the end bit is a period of time. During this period, the bus state changes as follows: SCL line maintains high level, while SDA line has a rising edge from low to high.
How do I remember the timing of the start and end signals of IIC communication? We regard IIC communication as a boat wandering in the water, regard the surface of the ship as SDA data line, and regard the undulation of the water as THE CLOCK SCK of IIC communication. Without water, the ship cannot go, and without clock line, there is no communication. Since SCL maintains a high level, the SDA line starts with a high-to-low drop along the initial signal, so we can use the bow as the initial signal (imagine a curved boat sailing downstream on a lake). Meanwhile, SCL maintains high level, and a rising edge from low to high on SDA line is the stop signal, so we can regard the stern as the stop signal (is the Angle between the stern of the boat and the water 45°). So if you can’t remember the timing of IIC communication, imagine you’re in a boat, you’re going down the river and you’re sitting on the boat and you’re writing the IIC driver on your computer.
I2C Data transfer format (Data bits &ACK)
- Each communication cycle is initiated and ended by the master device. The slave device only passively responds to the master device and cannot do anything on its own.
- In each communication cycle, the master device first sends 8-bit slave device address (in fact, there are only 7 bits of slave device address, and one bit indicates whether to write or read from the master device) to the bus (the master device sends the message in the form of broadcast, as long as all slave devices on the bus can receive this message). Each slave device on the bus then receives the address and compares it with its own device address to see if it is equal. If it is equal, it means that the main device is talking to me. If you don’t want to wait, it means that this communication has nothing to do with me, so don’t listen to it.
- After the sender sends a piece of data, the receiver needs to respond with an ACK. The response itself has only one bit and cannot carry valid information. It can only represent two meanings (either the received data, i.e., the valid response; No data received, invalid response). The ACK signal must be sent by the receiver because the receiver can reply only after the sender sends data.
- In a certain communication time, main equipment and from the device can only have one in hair (take the bus, that is, to the bus), the other at each clock, delay the ready to send data, send an ACK is valid response signal is only must be sent on the receiver, because only the sender can send data after receiving just reply a in charge (read) from the bus. If at some point both master and slave try to write to the bus that’s the end of the story, communication is messed up.
The protocol used to transfer data over a 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 starting bit and the following 8 CLKS are sent by the master device (master device controls the bus). At this time, the slave device can only read the bus to learn the information sent by the master device to the slave device. Then in cycle 9, the slave device is required by protocol to send an ACK to the master device, so the master device must release the bus (the master device sets the bus to high and then does not move, which is similar to the idle state of the bus) and issue an ACK when the slave device tries to pull the bus low. If the slave fails to pull down the bus, or if the slave does not pull down the bus at all, the master will see that the bus remains high through cycle 9. This means to the master that I did not receive an ACK, and the master will assume that the 8 bytes I just sent to the slave were not correct.
Software simulation protocol
1.IIC initialization function
Function: configure IIC clock line and data line
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 the code
Because it is software to simulate IIC, then we choose the pins of IIC communication is relatively random. The specific pins used can be referred to “STM32F1xx Specifications”, and it shall prevail. Here we choose PC11 and PC12 as IIC data and clock pins. Set it to push-pull output.
2. Initial 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: DATA changes from high to low when CLK is high
delay_us(4);
IIC_SCL=0;// Hold the I2C bus, ready to send or receive data
delay_us(4);
}
Copy the code
After the start signal is generated, all slave devices wait for the slave address signal immediately following STM32. On the IIC bus, each device’s address is unique. When the host broadcasts the same address as a device’s address, the device is selected. Unselected devices ignore subsequent data signals. Depending on the IIC protocol, this slave address can be 7 or 10 bits. After the address bit, there is the bit for selecting the transmission direction. If the bit is 0, the data transmission direction is from the host to the slave machine, that is, the host writes data to the slave machine. If the value is 1, the data is read by the slave machine.
3. Wait for the answer signal
Function: THE CPU generates a clock and reads the ACK response signal of the device
// Return value: 1, receive reply failed 0, receive reply succeeded
u8 IIC_Wait_Ack(void)
{
u8 re;
IIC_SDA=1; delay_us(1);// The CPU releases the SDA bus
IIC_SCL=1; delay_us(1);// SCL=1, then the device will return an ACK response
if(READ_SDA){// The CPU reads the status of the SDA interface
re=1;
}else{
re=0;
}
IIC_SCL=0;// The clock outputs 0
return re;
}
Copy the code
This function is used when STM32 acts as the sender to wait for and process the response or non-response signal from the receiver, that is, call the previous IIC_SendByte function before calling this function to detect the response. STM32 control SDA signal line output high resistance state, release its control over SDA, controlled by the receiver; Control THE SCL signal line to switch the high and low levels to generate a clock signal. According to the IIC protocol, if the receiver sets the SDA as low level, it means returning a “reply” signal; if the SDA remains high level, it means returning a “non-reply” signal. Between SCL switching between high and low levels, there is a delay to ensure that enough time is given for the receiver to return the reply signal. After the delay, macro SDA_READ is used to read the level of SDA line, and the value of re variable is given according to the level value. The function returns the value of re at the end, 0 if a response is received and 1 if no response is received. When STM32 acts as the data receiving end and calls the IIC_ReadByte function, it needs to return the reply or non-reply signal to the sender end. In this case, the IIC_Ack and IIC_Nack functions can be used for processing, which is opposite to the IIC_Wait_Ack function. The SDA line is also controlled by STM32.
4. Answer signal
CPU generates an ACK signal
The CPU generates an ACK signal
void IIC_Ack(void)
{
IIC_SDA=0;/ / CPU drives the SDA = 0
delay_us(2);
IIC_SCL=1;The CPU generates a clock
delay_us(2);
IIC_SCL=0;
delay_us(2);
IIC_SDA=1;// The CPU releases the SDA bus
}
// The CPU generates a NACK signal
void IIC_Nack (void)
{
IIC_SDA=1(a);/ / CPU drives the SDA = 1
delay_us(2);
IIC_SDA=1;//CPU generates 1 clock
delay_us(2);
IIC_SCL=0;
delay_us(2);
}
Copy the code
I2C transmits both data and address with a response. A response consists of two signals: ACK and NACK. When the device receives a byte of data or an address from the I2C, it needs to send an ACK signal to the other party to send the next data. If the receiver wishes to end the data transmission, it sends a “NACK” signal to the other party. After receiving this signal, the sender generates a stop signal to end the signal transmission. The specific process of the code is: according to the return of “reply” or “non-reply” signal, first prepare the level of THE SDA line. In the IIC_Ack function, set the SDA line to low level, indicating the “reply” signal. In the IIC_Nack function, set the SDA line to high level, indicating the “non-reply” signal. Control SCL line to switch between high and low levels to generate a clock signal, and add a delay between the high and low levels of SCL line to ensure that there is enough time for the other party to receive the level of SDA signal line; At the end of the IIC_Ack function, after the response signal is sent, the SDA line is set to high level again to release the control of the bus for the convenience of subsequent communication.
5. Stop signal
Function: CPU initiates I2C bus stop signal
{
IIC_SDA=0;//STOP: when CLK is at high level, SDA appears an up-modulation indicating IIC bus STOP signal
IIC_SCL=1;
delay_us(4);
IIC_SDA=1;// Send the I2C bus end signal
}
Copy the code
Stop signal can be done directly by looking at the sequence diagram. In the case that BOTH SCL and SDA are at low levels, first pull up the CLOCK line SCL, and then pull up the data line SDA, and IIC will end transmission. Above is the software simulation of IIC agreement, in the usual application we actually don’t need to master the specific code, just know the process principle of IIC agreement, should be generally speaking we use are all others to write good code, we only need to use is ok, if your code and I don’t have these from relationship, As long as the communication works, of course, if your design has some problems in the process, or does not display properly, our first concern is not the underlying protocol, but the other problems of your code.
6.IIC sends bytes
Function: CPU sends 8bit data to I2C bus device
void IIC_SendByte(u8 Byte)
{
u8 i;
/* Send the highest byte bit7 */ 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;// Free the bus
}
Byte <<= 1; /* Move a bit left */
delay_us(2); }}Copy the code
This function takes its input parameter as the one-byte data to be output using the I2C protocol. The body of the function is an 8-time for loop, which sends out one bit of data each time it executes. The loop ends with just that bit of data sent. The steps are broken down as follows: First, the program calculates “and” of input parameters Byte and 0x80 to judge the logical value of the highest bit. When it is 1, SDA outputs high level; when it is 0, SDA outputs low level. Then delay, in order to ensure that the output level of SDA line has been stable, then carry out subsequent operations; Then control SCL line to produce high and low level jump, that is, generate the COMMUNICATION clock of SCL line in I2C protocol; There is a delay between the high and low levels of SCL line, during which the SCL line maintains the high level. According to I2C protocol, the data is valid at this time, and the other party of communication will read the level logic of SDA line at this time. At the end of the loop, Byte moves one bit to the left for the next loop to send the next bit; For example, 8 data bits in Byte are sent out in the second cycle for 8 times. After the last bit is sent (at this time, the cycle counter I =7), the SDA line output is controlled to be 1 (i.e., high resistance state), that is, the sender releases THE SDA bus and waits for the response signal from the receiver.
7.IIC reads bytes
Function: CPU reads 8bit data from IIC bus device
u8_t IIC_ReadByte(void)
{
u8 i;
u8 value;
// Read bit7 with the first bit as data
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 the code
The IIC_ReadByte function also uses the for loop as the main body. The loop is executed eight times and receives one byte of data after execution. The loop body receives data as follows: First, a variable value is used to temporarily store the data to be received. Before each cycle starts, the value of value is moved 1 bit to the left to make room for the bit0 of value variable. Bit0 will be used to cache the latest received data bits, receive and shift bit by bit, and finally spell out the complete 8-bit data. Then control SCL line for high and low level switch, output I2C protocol communication clock; There is a delay between high and low level switching on THE SCL line, which ensures that sufficient time is given for the data sender to process. That is, the sender sends the level logic signal through the SDA signal line driven by the SCL clock. After this delay, STM32, as the data receiver, reads the level of the SDA signal line using the macro SDA_READ. If the signal line is 1, value++, that is, it sets its bit0 to 1, otherwise it will not operate (so that the bit will remain 0), so it reads a bit of data. Then, after the SCL line is switched to low level, delay is added so that the receiver can switch the SDA line output data as required. Until the end of the loop, the value variable contains 1 byte of data, which is returned as the function return value using return;
Hardware protocol
By contrast, hardware Iics use peripherals directly to control pins, reducing the CPU burden. However, when using hardware IIC, some fixed pins must be used as SCL and SDA, while software simulation IIC can use any GPIO pins, which is relatively flexible. The IIC peripheral of STM32 can be used as the host or slave of communication, supporting 100Kbit/s and 400Kbit/s rate, supporting 7-bit and 10-bit device address, supporting DMA data transmission, and data verification function. Its IIC peripherals also support SMBus2.0, a protocol similar to IIC that is mainly used in notebook battery management. STM32 chip has multiple IIC peripherals, and their IIC communication signals are led to different GPIO pins, which must be configured to these specified pins when used. For the multiplexing function of GPIO pins, please refer to THE “STM32F1xx Specification” and refer to it as the standard.
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 leakage 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 the code
Because the hardware IIC directly uses peripherals to control pins, the pins we choose for IIC communication are relatively fixed. The specific pins used can be referred to “STM32F1xx Specifications”, which shall prevail. It can be seen that two pins PB6 and PB7 can be used as the communication pins of IIC, and PB6 is the SCL clock line, while PB7 is the SDA data line, and is set as open leakage output. Why is this set to open leakage output mode? This is because the software is used to simulate the IIC mode, and THE GPIO of IIC protocol must have the open-leakage output mode. The open-leakage output mode actually outputs the high-resistance state when the output is high. When all devices on the IIC bus output the high-resistance state, the external pull-up resistor pulls up to the high level. In addition, when THE GPIO of STM32 is configured in open-miss output mode, it can still obtain the input level of external pins by reading the input data register of GPIO, that is to say, it also has the function of floating input mode. Therefore, there is no need to switch the MODE of GPIO when controlling the external output level of SDA line or reading the level signal of SDA line. In addition, under the IIC protocol, its start signal, wait for the response signal, response signal, stop signal and software simulation of the IIC protocol under the function is the same, here I will not repeat the explanation. Conclusion: IIC communication protocol is very simple, in the actual project we do not need to master the specific IIC protocol code, as long as we can use it, as the most common and commonly used protocol, we had better be able to recite or understand. Now IIC communication is not strange!