STM32 I2C Lecture 32 : Implementation of I2C master receive data API: Part 2

  • Post author:
  • Post category:Blog

 

Implementation of I2C master receive data API: Part 2

 

 


Procedure to read the data from slave when the length is greater than 1:

1. Clear the ADDR flag (Figure 1): The data reception begins only when you clear the ADDR flag.

Figure 1. Code to clear the ADDR flag.

 

2.Read the data until length becomes zero: Using for loop, read the data from the slave until the length becomes zero. To achieve this, you have to start reading data from i=Len to till i>0, as shown in Figure 2.

Figure 2. Code to read the data until the length becomes zero.

 

3. Wait until RXNE becomes 1 (Figure 3).

Implementation of I2C master receive data API: Part 2
Figure 3. Code to wait until RXNE becomes 1.

 

4.Check if the last 2 bytes are remaining (if (i=2)): 

  • Let’s assume that i is not equal to 2. Let’s assume i as 6, therefore length=6. Now when RXNE becomes 1, read the data and increment the buffer address. That means read the data into the buffer and increment the buffer address, as shown in Figure 4. You have to repeat this step until i becomes 2.
Implementation of I2C master receive data API: Part 2
Figure 4. Code to read the data until i=2.

 

  • When i becomes 2, clear the ACK bit or disable the Acking and then generate the STOP, as shown in Figure 5.
Implementation of I2C master receive data API: Part 2
Figure 5. Code to read the data when i=2.

 

This completes the master receive data. In the end, you have to re-enable the Acking (Figure 6) because when you enter into I2C_MasterReceiveData() API, the ACK was enabled. Therefore, before leaving this API, you have to re-enable the Acking only if ACK control is equal to I2C ACK enable in the config of I2C handle (Figure 7).

Implementation of I2C master receive data API: Part 2
Figure 6. Code to re-enable the Acking.

 

Implementation of I2C master receive data API: Part 2
Figure 7. Code to re-enable the Acking only if ACK control is equal to I2C ACK enable.

 

In the  following article, let’s do the exercise: Read data from the I2C slave.

 

FastBit Embedded Brain Academy Courses

Click here: https://fastbitlab.com/course1

FastBitLab

The FastBit Embedded Brain Academy uses the power of internet to bring the online courses related to the field of embedded system programming, Real time operating system, Embedded Linux systems, etc at your finger tip with very low cost. Backed with strong experience of industry, we have produced lots of courses with the customer enrolment over 3000+ across 100+ countries.