I2C slave support in driver
Now let’s implement all the callback events for slave transmitter and slave receiver.
Steps:
1. Go to the event IRQ handling section of the driver file shown in Figure 1.
2. In the TXE event, check for the device mode. If the device is master, then the code in Figure 2 will get executed.
The code to be executed when the device mode is a slave is implemented as follows:
- The TXE is nothing but a request for data.
- Call the application callback function and send handle and data request event as a parameter of the function, as shown in Figure 3.
Define I2C_EV_DATA_REQ macro in the I2C header (Figure 4).
The application callback function is called only if the slave is in transmitter mode. You can check the status register (SR2 shown in Figure 5) to see whether the device is in transmitter mode or receiver mode.
In status register 2, you will find TRA bit, which helps you understand whether the device is in transmitter mode or slave mode. If the TRA bit is zero, then the device is in receiver mode; if it is set, then the device is in transmitter mode.
- First, make sure that the slave is really in transmitter mode by using the if statement (Figure 6). If the TRA is set, then the device will be in transmitter mode, the TXE will also happen, and you can call the application callback function, as shown in Figure 6.
Remember that the TRA bit is influenced by the read-write bit of the address phase.
3. For the data receive, you have to change the RXNE event.
- The code to be executed when the device is in master mode is shown in Figure 7.
- Now let’s implement the else part, the code to be executed when the device is in slave mode.
First, make sure that the device is in receiver mode by checking the TRA bit of the SR2 register. If TRA is zero, then call the application callback function and send handle and I2C data receive event as a parameter of the function, as shown in Figure 8.
Define I2C_EV_DATA_RCV macro in the I2C header (Figure 9).
4. Implement the ACK failure (Figure 10) in the error IRQ handling. When the ACK failure happens, first, you have to clear the ACK failure and then send the event callback.
5. Generate the stop condition in the I2C event IRQ handling (Figure 11) since the stop is an event. When the stop occurs, you have to complete a clear sequence. After completing the clear sequence, call the application callback function for the stop event, as shown in Figure 11.
The master will not execute the code in Figure 11 since the STOPF is not applicable to the master.
6. Compile the code (Figure 12).
This completes the slave logic. For the slave, the application has to process the data request, and data receive event.
In the following article, let’s do the Exercise: I2C slave programming.
FastBit Embedded Brain Academy Courses
Click here: https://fastbitlab.com/course1