Implementation of I2C master sending data API:Part 4
Send data until length becomes 0:
Remember that before sending the data, first confirm whether the data register is empty or not. This is done by checking the TxE flag.
The code to send the data is, as shown in Figure 1.
- While length is greater than or equals zero, first check whether the TxE is set or not. If not, then wait till TxE is set.
- If TxE is set, send the data using pI2CHandle -> pI2Cx -> DR = “pTxbuffer” statement. Where pTxbuffer is used to get the data.
- Increment the pTxbuffer to get the next data and decrement the length.
- The while loop will keep sending the data until the length becomes zero. When length becomes zero, wait for TxE=1 and BTF=1 before generating the STOP condition (Figure 2).
- When TxE and BTF become 1, then generate the STOP condition, as shown in Figure 3.
- Create I2C_GenerateStopCondition() helper function to generate STOP condition, and its arguments are the same as that of I2C_GenerateStartCondition().
- To generate the STOP condition, set the 9th bit or STOP bit of the CR1 register. The STOP bit is set and cleared by software, cleared by hardware when a STOP condition is detected, set by hardware when a timeout error is detected.
- In master mode, if the STOP bit is 1, then the STOP generation after the current byte transfer or after the current START condition is sent. The I2C peripherals will not generate the STOP condition immediately; it waits until all the bits are transmitted out of the shift register.
- Use I2C_GenerateStopCondition() inside the I2C_MasterSendData(), as shown in Figure 4.