Implementation of I2C master sending data API:Part-1
Creation of API to send data:
- Creation of I2C_MasterSendData API in the driver.h file: Create an API with the name I2C_MasterSendData in a driver.h file, as shown in Figure 1. Inside this API, the first parameter is a handle, and the second one is the pointer to transmit the buffer. This pointer is a placeholder for the buffer address given by the user application. The third parameter is the length. The master needs the slave’s address in order to generate the address phase to send the data to the slave. So, the slave address is passed as a fourth parameter.
- Implement the I2C_MasterSendData API in driver.c file:
i. Generate the START condition: A small helper function I2C_GenerateStartCondition is created to generate the START condition. This API can be kept private to the driver since it is just a helper function. The prototype of I2C_GenerateStartCondition can be given at the beginning of the program; since it is a private function, no need to mention it in the driver.h file.
Look at Figure 2. The START bit is the 8th bit of the I2C_CR1 register. This bit is set and cleared by software and cleared by the hardware when the START is sent or PE=0. In master mode, the values shown in Figure 3 can be used to generate the START or repeated start. Let’s write the code for generating START, as shown in Figure 3.
ii. Confirm that START generation is completed by checking the SB flag in the SR1: Until SB is cleared, SCL will be stretched or pulled to low. Using a while statement, you can make the master wait until SB is set, as shown in Figure 4.
Create I2C related status flags definition section to define the flag macros, as shown in Figure 5.
Similarly, create the macros for ADDR, BTF, STOPF, BERR, ARLO, AF, OVR, and TIMEOUT flags of the I2C_SR1 register.
TIMEOUT (Timeout or Tlow error, shown in Figure 6): If TIMEOUT is set, the SCL remains LOW or stretched for 25ms (Timeout). When the device is in master mode, if the cumulative extend time of clock low or Tlow is more than 10ms, then the time out error will trigger. When this flag is set in master mode, the stop condition is automatically sent by the hardware, and the communication will be terminated.
FastBit Embedded Brain Academy Courses