1 /*
2  * Copyright (c) 2016, Freescale Semiconductor, Inc.
3  * Copyright 2016-2020 NXP
4  * All rights reserved.
5  *
6  * SPDX-License-Identifier: BSD-3-Clause
7  */
8 #include "fsl_i2c.h"
9 
10 /*******************************************************************************
11  * Definitions
12  ******************************************************************************/
13 
14 /* Component ID definition, used by tools. */
15 #ifndef FSL_COMPONENT_ID
16 #define FSL_COMPONENT_ID "platform.drivers.ii2c"
17 #endif
18 
19 /*! @brief i2c transfer state. */
20 enum _i2c_transfer_states
21 {
22     kIdleState             = 0x0U, /*!< I2C bus idle. */
23     kCheckAddressState     = 0x1U, /*!< 7-bit address check state. */
24     kSendCommandState      = 0x2U, /*!< Send command byte phase. */
25     kSendDataState         = 0x3U, /*!< Send data transfer phase. */
26     kReceiveDataBeginState = 0x4U, /*!< Receive data transfer phase begin. */
27     kReceiveDataState      = 0x5U, /*!< Receive data transfer phase. */
28 };
29 
30 /*! @brief Common sets of flags used by the driver. */
31 enum _i2c_flag_constants
32 {
33     kClearFlags = kI2C_ArbitrationLostFlag | kI2C_IntPendingFlag,
34     kIrqFlags   = kI2C_GlobalInterruptEnable,
35 };
36 
37 /*! @brief Typedef for interrupt handler. */
38 typedef void (*i2c_isr_t)(I2C_Type *base, void *i2cHandle);
39 
40 /*******************************************************************************
41  * Prototypes
42  ******************************************************************************/
43 
44 /*!
45  * @brief Get instance number for I2C module.
46  *
47  * @param base I2C peripheral base address.
48  */
49 static uint32_t I2C_GetInstance(I2C_Type *base);
50 
51 /*!
52  * @brief Set up master transfer, send slave address and decide the initial
53  * transfer state.
54  *
55  * @param base I2C peripheral base address.
56  * @param handle pointer to i2c_master_handle_t structure which stores the transfer state.
57  * @param xfer pointer to i2c_master_transfer_t structure.
58  */
59 static status_t I2C_InitTransferStateMachine(I2C_Type *base, i2c_master_handle_t *handle, i2c_master_transfer_t *xfer);
60 
61 /*!
62  * @brief Check and clear status operation.
63  *
64  * @param base I2C peripheral base address.
65  * @param status current i2c hardware status.
66  * @retval kStatus_Success No error found.
67  * @retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost.
68  * @retval kStatus_I2C_Nak Received Nak error.
69  */
70 static status_t I2C_CheckAndClearError(I2C_Type *base, uint32_t status);
71 
72 /*!
73  * @brief Master run transfer state machine to perform a byte of transfer.
74  *
75  * @param base I2C peripheral base address.
76  * @param handle pointer to i2c_master_handle_t structure which stores the transfer state
77  * @param isDone input param to get whether the thing is done, true is done
78  * @retval kStatus_Success No error found.
79  * @retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost.
80  * @retval kStatus_I2C_Nak Received Nak error.
81  * @retval kStatus_I2C_Timeout Transfer error, wait signal timeout.
82  */
83 static status_t I2C_MasterTransferRunStateMachine(I2C_Type *base, i2c_master_handle_t *handle, bool *isDone);
84 
85 /*!
86  * @brief I2C common interrupt handler.
87  *
88  * @param base I2C peripheral base address.
89  * @param handle pointer to i2c_master_handle_t structure which stores the transfer state
90  */
91 static void I2C_TransferCommonIRQHandler(I2C_Type *base, void *handle);
92 
93 /*!
94  * @brief Wait for status ready.
95  *
96  * @param base I2C peripheral base address.
97  * @param statusFlag statusFlag #_i2c_flags
98  * @retval kStatus_I2C_Timeout Wait signal timeout.
99  * @retval kStatus_Success Polling flag successfully.
100  */
101 static status_t I2C_WaitForStatusReady(I2C_Type *base, uint8_t statusFlag);
102 
103 /*******************************************************************************
104  * Variables
105  ******************************************************************************/
106 
107 /*! @brief SCL clock divider used to calculate baudrate. */
108 static const uint16_t s_i2cDividerTable[] = {
109     30,  32,  36,  42,  48,  52,  60,  72,  80,   88,   104,  128,  144,  160,  192,  240,
110     288, 320, 384, 480, 576, 640, 768, 960, 1152, 1280, 1536, 1920, 2304, 2560, 3072, 3840,
111     22,  24,  26,  28,  32,  36,  40,  44,  48,   56,   64,   72,   80,   96,   112,  128,
112     160, 192, 224, 256, 320, 384, 448, 512, 640,  768,  896,  1024, 1280, 1536, 1792, 2048};
113 
114 /*! @brief Pointers to i2c bases for each instance. */
115 static I2C_Type *const s_i2cBases[] = I2C_BASE_PTRS;
116 
117 /*! @brief Pointers to i2c IRQ number for each instance. */
118 static const IRQn_Type s_i2cIrqs[] = I2C_IRQS;
119 
120 #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
121 /*! @brief Pointers to i2c clocks for each instance. */
122 static const clock_ip_name_t s_i2cClocks[] = I2C_CLOCKS;
123 #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
124 
125 /*! @brief Pointers to i2c handles for each instance. */
126 static void *s_i2cHandle[ARRAY_SIZE(s_i2cBases)];
127 
128 /*! @brief Pointer to master IRQ handler for each instance. */
129 static i2c_isr_t s_i2cMasterIsr;
130 
131 /*! @brief Pointer to slave IRQ handler for each instance. */
132 static i2c_isr_t s_i2cSlaveIsr;
133 
134 /*******************************************************************************
135  * Codes
136  ******************************************************************************/
137 
I2C_GetInstance(I2C_Type * base)138 static uint32_t I2C_GetInstance(I2C_Type *base)
139 {
140     uint32_t instance;
141 
142     /* Find the instance index from base address mappings. */
143     for (instance = 0; instance < ARRAY_SIZE(s_i2cBases); instance++)
144     {
145         if (s_i2cBases[instance] == base)
146         {
147             break;
148         }
149     }
150 
151     assert(instance < ARRAY_SIZE(s_i2cBases));
152 
153     return instance;
154 }
155 
I2C_WaitForStatusReady(I2C_Type * base,uint8_t statusFlag)156 static status_t I2C_WaitForStatusReady(I2C_Type *base, uint8_t statusFlag)
157 {
158 #if I2C_RETRY_TIMES
159     uint32_t waitTimes = I2C_RETRY_TIMES;
160     /* Wait for TCF bit and manually trigger tx interrupt. */
161     while ((0U == (base->I2SR & statusFlag)) && (0U != --waitTimes))
162     {
163     }
164     if (0U == waitTimes)
165     {
166         return kStatus_I2C_Timeout;
167     }
168 #else
169     /* Wait for TCF bit and manually trigger tx interrupt. */
170     while (0U == (base->I2SR & statusFlag))
171     {
172     }
173 #endif
174     return kStatus_Success;
175 }
176 
I2C_InitTransferStateMachine(I2C_Type * base,i2c_master_handle_t * handle,i2c_master_transfer_t * xfer)177 static status_t I2C_InitTransferStateMachine(I2C_Type *base, i2c_master_handle_t *handle, i2c_master_transfer_t *xfer)
178 {
179     status_t result           = kStatus_Success;
180     i2c_direction_t direction = xfer->direction;
181 
182     /* Initialize the handle transfer information. */
183     handle->transfer = *xfer;
184 
185     /* Save total transfer size. */
186     handle->transferSize = xfer->dataSize;
187 
188     /* Initial transfer state. */
189     if (handle->transfer.subaddressSize > 0U)
190     {
191         if (xfer->direction == kI2C_Read)
192         {
193             direction = kI2C_Write;
194         }
195     }
196 
197     handle->state = (uint8_t)kCheckAddressState;
198 
199     /* Clear all status before transfer. */
200     I2C_MasterClearStatusFlags(base, (uint32_t)kClearFlags);
201 
202     /* Handle no start option. */
203     if ((handle->transfer.flags & (uint32_t)kI2C_TransferNoStartFlag) != 0U)
204     {
205         /* No need to send start flag, directly go to send command or data */
206         if (handle->transfer.subaddressSize > 0U)
207         {
208             handle->state = (uint8_t)kSendCommandState;
209         }
210         else
211         {
212             if (direction == kI2C_Write)
213             {
214                 /* Next state, send data. */
215                 handle->state = (uint8_t)kSendDataState;
216             }
217             else
218             {
219                 /* Only support write with no stop signal. */
220                 return kStatus_InvalidArgument;
221             }
222         }
223 
224         if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_TransferCompleteFlag) != kStatus_Success)
225         {
226             return kStatus_I2C_Timeout;
227         }
228         I2C_MasterTransferHandleIRQ(base, handle);
229     }
230     /* If repeated start is requested, send repeated start. */
231     else if ((handle->transfer.flags & (uint32_t)kI2C_TransferRepeatedStartFlag) != 0U)
232     {
233         result = I2C_MasterRepeatedStart(base, handle->transfer.slaveAddress, direction);
234     }
235     else /* For normal transfer, send start. */
236     {
237         result = I2C_MasterStart(base, handle->transfer.slaveAddress, direction);
238     }
239 
240     return result;
241 }
242 
I2C_CheckAndClearError(I2C_Type * base,uint32_t status)243 static status_t I2C_CheckAndClearError(I2C_Type *base, uint32_t status)
244 {
245     status_t result = kStatus_Success;
246 
247     /* Check arbitration lost. */
248     if ((status & (uint32_t)kI2C_ArbitrationLostFlag) != 0U)
249     {
250         /* Clear arbitration lost flag. */
251         base->I2SR &= (~(uint8_t)kI2C_ArbitrationLostFlag);
252 
253         /* Reset I2C controller*/
254         base->I2CR &= ~(uint16_t)I2C_I2CR_IEN_MASK;
255         base->I2CR |= I2C_I2CR_IEN_MASK;
256 
257         result = kStatus_I2C_ArbitrationLost;
258     }
259     /* Check NAK */
260     else if ((status & (uint32_t)kI2C_ReceiveNakFlag) != 0U)
261     {
262         result = kStatus_I2C_Nak;
263     }
264     else
265     {
266         /* Avoid MISRA 2012 rule 15.7 violation */
267     }
268 
269     return result;
270 }
271 
I2C_MasterTransferRunStateMachine(I2C_Type * base,i2c_master_handle_t * handle,bool * isDone)272 static status_t I2C_MasterTransferRunStateMachine(I2C_Type *base, i2c_master_handle_t *handle, bool *isDone)
273 {
274     status_t result        = kStatus_Success;
275     uint32_t statusFlags   = base->I2SR;
276     *isDone                = false;
277     volatile uint8_t dummy = 0U;
278     bool ignoreNak         = ((handle->state == (uint8_t)kSendDataState) && (handle->transfer.dataSize == 0U)) ||
279                      ((handle->state == (uint8_t)kReceiveDataState) && (handle->transfer.dataSize == 1U));
280 
281     /* Add this to avoid build warning. */
282     dummy++;
283 
284     /* Check & clear error flags. */
285     result = I2C_CheckAndClearError(base, statusFlags);
286 
287     /* Ignore Nak when it's appeared for last byte. */
288     if ((result == kStatus_I2C_Nak) && ignoreNak)
289     {
290         result = kStatus_Success;
291     }
292 
293     /* Handle Check address state to check the slave address is Acked in slave
294        probe application. */
295     if (handle->state == (uint8_t)kCheckAddressState)
296     {
297         if ((statusFlags & (uint32_t)kI2C_ReceiveNakFlag) != 0U)
298         {
299             result = kStatus_I2C_Addr_Nak;
300         }
301         else
302         {
303             if (handle->transfer.subaddressSize > 0U)
304             {
305                 handle->state = (uint8_t)kSendCommandState;
306             }
307             else
308             {
309                 if (handle->transfer.direction == kI2C_Write)
310                 {
311                     /* Next state, send data. */
312                     handle->state = (uint8_t)kSendDataState;
313                 }
314                 else
315                 {
316                     /* Next state, receive data begin. */
317                     handle->state = (uint8_t)kReceiveDataBeginState;
318                 }
319             }
320         }
321     }
322 
323     if (result != kStatus_Success)
324     {
325         return result;
326     }
327 
328     /* Run state machine. */
329     switch (handle->state)
330     {
331         /* Send I2C command. */
332         case (uint8_t)kSendCommandState:
333             if (handle->transfer.subaddressSize != 0U)
334             {
335                 handle->transfer.subaddressSize--;
336                 base->I2DR = (uint16_t)((handle->transfer.subaddress) >> (8U * handle->transfer.subaddressSize));
337             }
338             else
339             {
340                 if (handle->transfer.direction == kI2C_Write)
341                 {
342                     /* Send first byte of data. */
343                     if (handle->transfer.dataSize > 0U)
344                     {
345                         /* Next state, send data. */
346                         handle->state = (uint8_t)kSendDataState;
347                         base->I2DR    = *handle->transfer.data;
348                         handle->transfer.data++;
349                         handle->transfer.dataSize--;
350                     }
351                     else
352                     {
353                         *isDone = true;
354                     }
355                 }
356                 else
357                 {
358                     /* Send repeated start and slave address. */
359                     result = I2C_MasterRepeatedStart(base, handle->transfer.slaveAddress, kI2C_Read);
360 
361                     /* Next state, receive data begin. */
362                     handle->state = (uint8_t)kReceiveDataBeginState;
363                 }
364             }
365             break;
366 
367         /* Send I2C data. */
368         case (uint8_t)kSendDataState:
369             /* Send one byte of data. */
370             if (handle->transfer.dataSize > 0U)
371             {
372                 base->I2DR = *handle->transfer.data;
373                 handle->transfer.data++;
374                 handle->transfer.dataSize--;
375             }
376             else
377             {
378                 *isDone = true;
379             }
380             break;
381 
382         /* Start I2C data receive. */
383         case (uint8_t)kReceiveDataBeginState:
384             base->I2CR &= ~((uint16_t)I2C_I2CR_MTX_MASK | (uint16_t)I2C_I2CR_TXAK_MASK);
385 
386             /* Send nak at the last receive byte. */
387             if (handle->transfer.dataSize == 1U)
388             {
389                 base->I2CR |= I2C_I2CR_TXAK_MASK;
390             }
391 
392             /* Read dummy to release the bus. */
393             dummy = (uint8_t)base->I2DR;
394 
395             /* Next state, receive data. */
396             handle->state = (uint8_t)kReceiveDataState;
397             break;
398 
399         /* Receive I2C data. */
400         case (uint8_t)kReceiveDataState:
401             /* Receive one byte of data. */
402             if (0U != handle->transfer.dataSize--)
403             {
404                 if (handle->transfer.dataSize == 0U)
405                 {
406                     *isDone = true;
407 
408                     /* Send stop if kI2C_TransferNoStop is not asserted. */
409                     if (0U == (handle->transfer.flags & (uint32_t)kI2C_TransferNoStopFlag))
410                     {
411                         result = I2C_MasterStop(base);
412                     }
413                     else
414                     {
415                         base->I2CR |= I2C_I2CR_MTX_MASK;
416                     }
417                 }
418 
419                 /* Send NAK at the last receive byte. */
420                 if (handle->transfer.dataSize == 1U)
421                 {
422                     base->I2CR |= I2C_I2CR_TXAK_MASK;
423                 }
424 
425                 /* Read the data byte into the transfer buffer. */
426                 *handle->transfer.data = (uint8_t)base->I2DR;
427                 handle->transfer.data++;
428             }
429             break;
430 
431         default:
432             assert(false);
433             break;
434     }
435 
436     return result;
437 }
438 
I2C_TransferCommonIRQHandler(I2C_Type * base,void * handle)439 static void I2C_TransferCommonIRQHandler(I2C_Type *base, void *handle)
440 {
441     /* Check if master interrupt. */
442     if (((base->I2SR & (uint8_t)kI2C_ArbitrationLostFlag) != 0U) || ((base->I2CR & (uint8_t)I2C_I2CR_MSTA_MASK) != 0U))
443     {
444         s_i2cMasterIsr(base, handle);
445     }
446     else
447     {
448         s_i2cSlaveIsr(base, handle);
449     }
450     SDK_ISR_EXIT_BARRIER;
451 }
452 
453 /*!
454  * brief Initializes the I2C peripheral. Call this API to ungate the I2C clock
455  * and configure the I2C with master configuration.
456  *
457  * note This API should be called at the beginning of the application.
458  * Otherwise, any operation to the I2C module can cause a hard fault
459  * because the clock is not enabled. The configuration structure can be custom filled
460  * or it can be set with default values by using the I2C_MasterGetDefaultConfig().
461  * After calling this API, the master is ready to transfer.
462  * This is an example.
463  * code
464  * i2c_master_config_t config = {
465  * .enableMaster = true,
466  * .baudRate_Bps = 100000
467  * };
468  * I2C_MasterInit(I2C0, &config, 12000000U);
469  * endcode
470  *
471  * param base I2C base pointer
472  * param masterConfig A pointer to the master configuration structure
473  * param srcClock_Hz I2C peripheral clock frequency in Hz
474  */
I2C_MasterInit(I2C_Type * base,const i2c_master_config_t * masterConfig,uint32_t srcClock_Hz)475 void I2C_MasterInit(I2C_Type *base, const i2c_master_config_t *masterConfig, uint32_t srcClock_Hz)
476 {
477     assert((masterConfig != NULL) && (srcClock_Hz != 0U));
478 
479 #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
480     /* Enable I2C clock. */
481     CLOCK_EnableClock(s_i2cClocks[I2C_GetInstance(base)]);
482 #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
483 
484     /* Reset the module. */
485     base->IADR = 0;
486     base->IFDR = 0;
487     base->I2CR = 0;
488     base->I2SR = 0;
489 
490     /* Disable I2C prior to configuring it. */
491     base->I2CR &= ~((uint16_t)I2C_I2CR_IEN_MASK);
492 
493     /* Clear all flags. */
494     I2C_MasterClearStatusFlags(base, (uint32_t)kClearFlags);
495 
496     /* Configure baud rate. */
497     I2C_MasterSetBaudRate(base, masterConfig->baudRate_Bps, srcClock_Hz);
498 
499     /* Enable the I2C peripheral based on the configuration. */
500     base->I2CR = I2C_I2CR_IEN(masterConfig->enableMaster);
501 }
502 
503 /*!
504  * brief De-initializes the I2C master peripheral. Call this API to gate the I2C clock.
505  * The I2C master module can't work unless the I2C_MasterInit is called.
506  * param base I2C base pointer
507  */
I2C_MasterDeinit(I2C_Type * base)508 void I2C_MasterDeinit(I2C_Type *base)
509 {
510     /* Disable I2C module. */
511     I2C_Enable(base, false);
512 
513 #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
514     /* Disable I2C clock. */
515     CLOCK_DisableClock(s_i2cClocks[I2C_GetInstance(base)]);
516 #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
517 }
518 
519 /*!
520  * brief  Sets the I2C master configuration structure to default values.
521  *
522  * The purpose of this API is to get the configuration structure initialized for use in the I2C_MasterInit().
523  * Use the initialized structure unchanged in the I2C_MasterInit() or modify
524  * the structure before calling the I2C_MasterInit().
525  * This is an example.
526  * code
527  * i2c_master_config_t config;
528  * I2C_MasterGetDefaultConfig(&config);
529  * endcode
530  * param masterConfig A pointer to the master configuration structure.
531  */
I2C_MasterGetDefaultConfig(i2c_master_config_t * masterConfig)532 void I2C_MasterGetDefaultConfig(i2c_master_config_t *masterConfig)
533 {
534     assert(masterConfig != NULL);
535 
536     /* Initializes the configure structure to zero. */
537     (void)memset(masterConfig, 0, sizeof(*masterConfig));
538 
539     /* Default baud rate at 100kbps. */
540     masterConfig->baudRate_Bps = 100000U;
541 
542     /* Enable the I2C peripheral. */
543     masterConfig->enableMaster = true;
544 }
545 
546 /*!
547  * brief Enables I2C interrupt requests.
548  *
549  * param base I2C base pointer
550  * param mask interrupt source
551  *     The parameter can be combination of the following source if defined:
552  *     arg kI2C_GlobalInterruptEnable
553  *     arg kI2C_StopDetectInterruptEnable/kI2C_StartDetectInterruptEnable
554  *     arg kI2C_SdaTimeoutInterruptEnable
555  */
I2C_EnableInterrupts(I2C_Type * base,uint32_t mask)556 void I2C_EnableInterrupts(I2C_Type *base, uint32_t mask)
557 {
558     if ((mask & (uint32_t)kI2C_GlobalInterruptEnable) != 0U)
559     {
560         base->I2CR |= I2C_I2CR_IIEN_MASK;
561     }
562 }
563 
564 /*!
565  * brief Disables I2C interrupt requests.
566  *
567  * param base I2C base pointer
568  * param mask interrupt source
569  *     The parameter can be combination of the following source if defined:
570  *     arg kI2C_GlobalInterruptEnable
571  *     arg kI2C_StopDetectInterruptEnable/kI2C_StartDetectInterruptEnable
572  *     arg kI2C_SdaTimeoutInterruptEnable
573  */
I2C_DisableInterrupts(I2C_Type * base,uint32_t mask)574 void I2C_DisableInterrupts(I2C_Type *base, uint32_t mask)
575 {
576     if ((mask & (uint32_t)kI2C_GlobalInterruptEnable) != 0U)
577     {
578         base->I2CR &= ~(uint16_t)I2C_I2CR_IIEN_MASK;
579     }
580 }
581 
582 /*!
583  * brief Sets the I2C master transfer baud rate.
584  *
585  * param base I2C base pointer
586  * param baudRate_Bps the baud rate value in bps
587  * param srcClock_Hz Source clock
588  */
I2C_MasterSetBaudRate(I2C_Type * base,uint32_t baudRate_Bps,uint32_t srcClock_Hz)589 void I2C_MasterSetBaudRate(I2C_Type *base, uint32_t baudRate_Bps, uint32_t srcClock_Hz)
590 {
591     uint32_t computedRate;
592     uint32_t absError;
593     uint32_t bestError = UINT32_MAX;
594     uint32_t bestIcr   = 0u;
595     uint8_t i;
596 
597     /* Scan table to find best match. */
598     for (i = 0u; i < sizeof(s_i2cDividerTable) / sizeof(s_i2cDividerTable[0]); ++i)
599     {
600         computedRate = srcClock_Hz / s_i2cDividerTable[i];
601         absError     = baudRate_Bps > computedRate ? (baudRate_Bps - computedRate) : (computedRate - baudRate_Bps);
602 
603         if (absError < bestError)
604         {
605             bestIcr   = i;
606             bestError = absError;
607 
608             /* If the error is 0, then we can stop searching because we won't find a better match. */
609             if (absError == 0U)
610             {
611                 break;
612             }
613         }
614     }
615 
616     /* Set frequency register based on best settings. */
617     base->IFDR = I2C_IFDR_IC(bestIcr);
618 }
619 
620 /*!
621  * brief Sends a START on the I2C bus.
622  *
623  * This function is used to initiate a new master mode transfer by sending the START signal.
624  * The slave address is sent following the I2C START signal.
625  *
626  * param base I2C peripheral base pointer
627  * param address 7-bit slave device address.
628  * param direction Master transfer directions(transmit/receive).
629  * retval kStatus_Success Successfully send the start signal.
630  * retval kStatus_I2C_Busy Current bus is busy.
631  */
I2C_MasterStart(I2C_Type * base,uint8_t address,i2c_direction_t direction)632 status_t I2C_MasterStart(I2C_Type *base, uint8_t address, i2c_direction_t direction)
633 {
634     status_t result      = kStatus_Success;
635     uint32_t statusFlags = I2C_MasterGetStatusFlags(base);
636 
637     /* Return an error if the bus is already in use. */
638     if ((statusFlags & (uint32_t)kI2C_BusBusyFlag) != 0U)
639     {
640         result = kStatus_I2C_Busy;
641     }
642     else
643     {
644         /* Send the START signal. */
645         base->I2CR |= I2C_I2CR_MSTA_MASK | I2C_I2CR_MTX_MASK;
646 
647         base->I2DR = (uint16_t)(((uint32_t)address) << 1U | ((direction == kI2C_Read) ? 1U : 0U));
648     }
649 
650     return result;
651 }
652 
653 /*!
654  * brief Sends a REPEATED START on the I2C bus.
655  *
656  * param base I2C peripheral base pointer
657  * param address 7-bit slave device address.
658  * param direction Master transfer directions(transmit/receive).
659  * retval kStatus_Success Successfully send the start signal.
660  * retval kStatus_I2C_Busy Current bus is busy but not occupied by current I2C master.
661  */
I2C_MasterRepeatedStart(I2C_Type * base,uint8_t address,i2c_direction_t direction)662 status_t I2C_MasterRepeatedStart(I2C_Type *base, uint8_t address, i2c_direction_t direction)
663 {
664     status_t result      = kStatus_Success;
665     uint32_t statusFlags = I2C_MasterGetStatusFlags(base);
666 
667     /* Return an error if the bus is already in use, but not by us. */
668     if (((statusFlags & (uint32_t)kI2C_BusBusyFlag) != 0U) && ((base->I2CR & (uint16_t)I2C_I2CR_MSTA_MASK) == 0U))
669     {
670         result = kStatus_I2C_Busy;
671     }
672     else
673     {
674         /* We are already in a transfer, so send a repeated start. */
675         base->I2CR |= I2C_I2CR_RSTA_MASK | I2C_I2CR_MTX_MASK;
676 
677         base->I2DR = (uint16_t)(((uint32_t)address) << 1U | ((direction == kI2C_Read) ? 1U : 0U));
678     }
679 
680     return result;
681 }
682 
683 /*!
684  * brief Sends a STOP signal on the I2C bus.
685  *
686  * retval kStatus_Success Successfully send the stop signal.
687  * retval kStatus_I2C_Timeout Send stop signal failed, timeout.
688  */
I2C_MasterStop(I2C_Type * base)689 status_t I2C_MasterStop(I2C_Type *base)
690 {
691     /* Issue the STOP command on the bus. */
692     base->I2CR &= ~((uint16_t)I2C_I2CR_MSTA_MASK | (uint16_t)I2C_I2CR_MTX_MASK | (uint16_t)I2C_I2CR_TXAK_MASK);
693 
694 #if I2C_RETRY_TIMES
695     uint32_t waitTimes = I2C_RETRY_TIMES;
696     /* Wait for IBB bit is cleared. */
697     while ((0U != (base->I2SR & (uint8_t)kI2C_BusBusyFlag)) && (0U != --waitTimes))
698     {
699     }
700     if (0U == waitTimes)
701     {
702         return kStatus_I2C_Timeout;
703     }
704 #else
705     /* Wait for IBB bit is cleared. */
706     while (0U != (base->I2SR & (uint8_t)kI2C_BusBusyFlag))
707     {
708     }
709 #endif
710     return kStatus_Success;
711 }
712 
713 /*!
714  * brief Performs a polling send transaction on the I2C bus.
715  *
716  * param base  The I2C peripheral base pointer.
717  * param txBuff The pointer to the data to be transferred.
718  * param txSize The length in bytes of the data to be transferred.
719  * param flags Transfer control flag to decide whether need to send a stop, use kI2C_TransferDefaultFlag
720  *  to issue a stop and kI2C_TransferNoStop to not send a stop.
721  * retval kStatus_Success Successfully complete the data transmission.
722  * retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost.
723  * retval kStataus_I2C_Nak Transfer error, receive NAK during transfer.
724  */
I2C_MasterWriteBlocking(I2C_Type * base,const uint8_t * txBuff,size_t txSize,uint32_t flags)725 status_t I2C_MasterWriteBlocking(I2C_Type *base, const uint8_t *txBuff, size_t txSize, uint32_t flags)
726 {
727     status_t result     = kStatus_Success;
728     uint8_t statusFlags = 0;
729 
730     if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_TransferCompleteFlag) != kStatus_Success)
731     {
732         return kStatus_I2C_Timeout;
733     }
734 
735     /* Clear the IICIF flag. */
736     base->I2SR &= ~(uint16_t)kI2C_IntPendingFlag;
737 
738     /* Setup the I2C peripheral to transmit data. */
739     base->I2CR |= I2C_I2CR_MTX_MASK;
740 
741     while (0U != txSize--)
742     {
743         /* Send a byte of data. */
744         base->I2DR = *txBuff++;
745 
746         if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_IntPendingFlag) != kStatus_Success)
747         {
748             return kStatus_I2C_Timeout;
749         }
750 
751         statusFlags = (uint8_t)base->I2SR;
752 
753         /* Clear the IICIF flag. */
754         base->I2SR &= ~(uint16_t)kI2C_IntPendingFlag;
755 
756         /* Check if arbitration lost or no acknowledgement (NAK), return failure status. */
757         if ((statusFlags & (uint8_t)kI2C_ArbitrationLostFlag) != 0U)
758         {
759             base->I2SR = (uint16_t)kI2C_ArbitrationLostFlag;
760             result     = kStatus_I2C_ArbitrationLost;
761         }
762 
763         if (((statusFlags & (uint8_t)kI2C_ReceiveNakFlag) != 0U) && (txSize != 0U))
764         {
765             base->I2SR = (uint16_t)kI2C_ReceiveNakFlag;
766             result     = kStatus_I2C_Nak;
767         }
768 
769         if (result != kStatus_Success)
770         {
771             /* Breaking out of the send loop. */
772             break;
773         }
774     }
775 
776     if (((result == kStatus_Success) && (0U == (flags & (uint32_t)kI2C_TransferNoStopFlag))) ||
777         (result == kStatus_I2C_Nak))
778     {
779         /* Clear the IICIF flag. */
780         base->I2SR &= ~(uint16_t)kI2C_IntPendingFlag;
781 
782         /* Send stop. */
783         result = I2C_MasterStop(base);
784     }
785 
786     return result;
787 }
788 
789 /*!
790  * brief Performs a polling receive transaction on the I2C bus.
791  *
792  * note The I2C_MasterReadBlocking function stops the bus before reading the final byte.
793  * Without stopping the bus prior for the final read, the bus issues another read, resulting
794  * in garbage data being read into the data register.
795  *
796  * param base I2C peripheral base pointer.
797  * param rxBuff The pointer to the data to store the received data.
798  * param rxSize The length in bytes of the data to be received.
799  * param flags Transfer control flag to decide whether need to send a stop, use kI2C_TransferDefaultFlag
800  *  to issue a stop and kI2C_TransferNoStop to not send a stop.
801  * retval kStatus_Success Successfully complete the data transmission.
802  * retval kStatus_I2C_Timeout Send stop signal failed, timeout.
803  */
I2C_MasterReadBlocking(I2C_Type * base,uint8_t * rxBuff,size_t rxSize,uint32_t flags)804 status_t I2C_MasterReadBlocking(I2C_Type *base, uint8_t *rxBuff, size_t rxSize, uint32_t flags)
805 {
806     status_t result        = kStatus_Success;
807     volatile uint8_t dummy = 0;
808 
809     /* Add this to avoid build warning. */
810     dummy++;
811 
812     if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_TransferCompleteFlag) != kStatus_Success)
813     {
814         return kStatus_I2C_Timeout;
815     }
816 
817     /* Clear the IICIF flag. */
818     base->I2SR &= ~(uint16_t)kI2C_IntPendingFlag;
819 
820     /* Setup the I2C peripheral to receive data. */
821     base->I2CR &= ~((uint16_t)I2C_I2CR_MTX_MASK | (uint16_t)I2C_I2CR_TXAK_MASK);
822 
823     /* If rxSize equals 1, configure to send NAK. */
824     if (rxSize == 1U)
825     {
826         /* Issue NACK on read. */
827         base->I2CR |= I2C_I2CR_TXAK_MASK;
828     }
829 
830     /* Do dummy read. */
831     dummy = (uint8_t)base->I2DR;
832 
833     while (0U != (rxSize--))
834     {
835         if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_IntPendingFlag) != kStatus_Success)
836         {
837             return kStatus_I2C_Timeout;
838         }
839 
840         /* Clear the IICIF flag. */
841         base->I2SR &= ~(uint16_t)kI2C_IntPendingFlag;
842 
843         /* Single byte use case. */
844         if (rxSize == 0U)
845         {
846             if (0U == (flags & (uint32_t)kI2C_TransferNoStopFlag))
847             {
848                 /* Issue STOP command before reading last byte. */
849                 result = I2C_MasterStop(base);
850             }
851             else
852             {
853                 /* Change direction to Tx to avoid extra clocks. */
854                 base->I2CR |= I2C_I2CR_MTX_MASK;
855             }
856         }
857 
858         if (rxSize == 1U)
859         {
860             /* Issue NACK on read. */
861             base->I2CR |= I2C_I2CR_TXAK_MASK;
862         }
863 
864         /* Read from the data register. */
865         *rxBuff++ = (uint8_t)base->I2DR;
866     }
867 
868     return result;
869 }
870 
871 /*!
872  * brief Performs a master polling transfer on the I2C bus.
873  *
874  * note The API does not return until the transfer succeeds or fails due
875  * to arbitration lost or receiving a NAK.
876  *
877  * param base I2C peripheral base address.
878  * param xfer Pointer to the transfer structure.
879  * retval kStatus_Success Successfully complete the data transmission.
880  * retval kStatus_I2C_Busy Previous transmission still not finished.
881  * retval kStatus_I2C_Timeout Transfer error, wait signal timeout.
882  * retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost.
883  * retval kStataus_I2C_Nak Transfer error, receive NAK during transfer.
884  */
I2C_MasterTransferBlocking(I2C_Type * base,i2c_master_transfer_t * xfer)885 status_t I2C_MasterTransferBlocking(I2C_Type *base, i2c_master_transfer_t *xfer)
886 {
887     assert(xfer != NULL);
888 
889     i2c_direction_t direction = xfer->direction;
890     status_t result           = kStatus_Success;
891 
892     /* Clear all status before transfer. */
893     I2C_MasterClearStatusFlags(base, (uint32_t)kClearFlags);
894 
895     if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_TransferCompleteFlag) != kStatus_Success)
896     {
897         return kStatus_I2C_Timeout;
898     }
899 
900     /* Change to send write address when it's a read operation with command. */
901     if ((xfer->subaddressSize > 0U) && (xfer->direction == kI2C_Read))
902     {
903         direction = kI2C_Write;
904     }
905 
906     /* Handle no start option, only support write with no start signal. */
907     if ((xfer->flags & (uint32_t)kI2C_TransferNoStartFlag) != 0U)
908     {
909         if (direction == kI2C_Read)
910         {
911             return kStatus_InvalidArgument;
912         }
913     }
914     /* If repeated start is requested, send repeated start. */
915     else if ((xfer->flags & (uint32_t)kI2C_TransferRepeatedStartFlag) != 0U)
916     {
917         result = I2C_MasterRepeatedStart(base, xfer->slaveAddress, direction);
918     }
919     else /* For normal transfer, send start. */
920     {
921         result = I2C_MasterStart(base, xfer->slaveAddress, direction);
922     }
923 
924     if (0U == (xfer->flags & (uint32_t)kI2C_TransferNoStartFlag))
925     {
926         /* Return if error. */
927         if (result != kStatus_Success)
928         {
929             return result;
930         }
931 
932         if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_IntPendingFlag) != kStatus_Success)
933         {
934             return kStatus_I2C_Timeout;
935         }
936 
937         /* Check if there's transfer error. */
938         result = I2C_CheckAndClearError(base, base->I2SR);
939 
940         /* Return if error. */
941         if (result != kStatus_Success)
942         {
943             if (result == kStatus_I2C_Nak)
944             {
945                 result = kStatus_I2C_Addr_Nak;
946 
947                 (void)I2C_MasterStop(base);
948             }
949 
950             return result;
951         }
952     }
953 
954     /* Send subaddress. */
955     if (xfer->subaddressSize != 0U)
956     {
957         do
958         {
959             /* Clear interrupt pending flag. */
960             base->I2SR &= ~(uint16_t)kI2C_IntPendingFlag;
961 
962             xfer->subaddressSize--;
963             base->I2DR = (uint16_t)((xfer->subaddress) >> (8U * xfer->subaddressSize));
964 
965             if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_IntPendingFlag) != kStatus_Success)
966             {
967                 return kStatus_I2C_Timeout;
968             }
969 
970             /* Check if there's transfer error. */
971             result = I2C_CheckAndClearError(base, base->I2SR);
972 
973             if (result != kStatus_Success)
974             {
975                 if (result == kStatus_I2C_Nak)
976                 {
977                     (void)I2C_MasterStop(base);
978                 }
979 
980                 return result;
981             }
982 
983         } while (xfer->subaddressSize > 0U);
984 
985         if (xfer->direction == kI2C_Read)
986         {
987             /* Clear pending flag. */
988             base->I2SR &= ~(uint16_t)kI2C_IntPendingFlag;
989 
990             /* Send repeated start and slave address. */
991             result = I2C_MasterRepeatedStart(base, xfer->slaveAddress, kI2C_Read);
992 
993             /* Return if error. */
994             if (result != kStatus_Success)
995             {
996                 return result;
997             }
998 
999             if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_IntPendingFlag) != kStatus_Success)
1000             {
1001                 return kStatus_I2C_Timeout;
1002             }
1003 
1004             /* Check if there's transfer error. */
1005             result = I2C_CheckAndClearError(base, base->I2SR);
1006 
1007             if (result != kStatus_Success)
1008             {
1009                 if (result == kStatus_I2C_Nak)
1010                 {
1011                     result = kStatus_I2C_Addr_Nak;
1012 
1013                     (void)I2C_MasterStop(base);
1014                 }
1015 
1016                 return result;
1017             }
1018         }
1019     }
1020 
1021     /* Transmit data. */
1022     if (xfer->direction == kI2C_Write)
1023     {
1024         if (xfer->dataSize > 0U)
1025         {
1026             /* Send Data. */
1027             result = I2C_MasterWriteBlocking(base, xfer->data, xfer->dataSize, xfer->flags);
1028         }
1029         else if (0U == (xfer->flags & (uint32_t)kI2C_TransferNoStopFlag))
1030         {
1031             /* Send stop. */
1032             result = I2C_MasterStop(base);
1033         }
1034         else
1035         {
1036             /* Avoid MISRA 2012 rule 15.7 violation */
1037         }
1038     }
1039     /* Receive Data. */
1040     if ((xfer->direction == kI2C_Read) && (xfer->dataSize > 0U))
1041     {
1042         result = I2C_MasterReadBlocking(base, xfer->data, xfer->dataSize, xfer->flags);
1043     }
1044 
1045     return result;
1046 }
1047 
1048 /*!
1049  * brief Initializes the I2C handle which is used in transactional functions.
1050  *
1051  * param base I2C base pointer.
1052  * param handle pointer to i2c_master_handle_t structure to store the transfer state.
1053  * param callback pointer to user callback function.
1054  * param userData user parameter passed to the callback function.
1055  */
I2C_MasterTransferCreateHandle(I2C_Type * base,i2c_master_handle_t * handle,i2c_master_transfer_callback_t callback,void * userData)1056 void I2C_MasterTransferCreateHandle(I2C_Type *base,
1057                                     i2c_master_handle_t *handle,
1058                                     i2c_master_transfer_callback_t callback,
1059                                     void *userData)
1060 {
1061     assert(handle != NULL);
1062 
1063     uint32_t instance = I2C_GetInstance(base);
1064 
1065     /* Zero handle. */
1066     (void)memset(handle, 0, sizeof(*handle));
1067 
1068     /* Set callback and userData. */
1069     handle->completionCallback = callback;
1070     handle->userData           = userData;
1071 
1072     /* Save the context in global variables to support the double weak mechanism. */
1073     s_i2cHandle[instance] = handle;
1074 
1075     /* Save master interrupt handler. */
1076     s_i2cMasterIsr = I2C_MasterTransferHandleIRQ;
1077 
1078     /* Enable NVIC interrupt. */
1079     (void)EnableIRQ(s_i2cIrqs[instance]);
1080 }
1081 
1082 /*!
1083  * brief Performs a master interrupt non-blocking transfer on the I2C bus.
1084  *
1085  * note Calling the API returns immediately after transfer initiates. The user needs
1086  * to call I2C_MasterGetTransferCount to poll the transfer status to check whether
1087  * the transfer is finished. If the return status is not kStatus_I2C_Busy, the transfer
1088  * is finished.
1089  *
1090  * param base I2C base pointer.
1091  * param handle pointer to i2c_master_handle_t structure which stores the transfer state.
1092  * param xfer pointer to i2c_master_transfer_t structure.
1093  * retval kStatus_Success Successfully start the data transmission.
1094  * retval kStatus_I2C_Busy Previous transmission still not finished.
1095  * retval kStatus_I2C_Timeout Transfer error, wait signal timeout.
1096  */
I2C_MasterTransferNonBlocking(I2C_Type * base,i2c_master_handle_t * handle,i2c_master_transfer_t * xfer)1097 status_t I2C_MasterTransferNonBlocking(I2C_Type *base, i2c_master_handle_t *handle, i2c_master_transfer_t *xfer)
1098 {
1099     assert(handle != NULL);
1100     assert(xfer != NULL);
1101 
1102     status_t result = kStatus_Success;
1103 
1104     /* Check if the I2C bus is idle - if not return busy status. */
1105     if (handle->state != (uint8_t)kIdleState)
1106     {
1107         result = kStatus_I2C_Busy;
1108     }
1109     else
1110     {
1111         /* Start up the master transfer state machine. */
1112         result = I2C_InitTransferStateMachine(base, handle, xfer);
1113 
1114         if (result == kStatus_Success)
1115         {
1116             /* Enable the I2C interrupts. */
1117             I2C_EnableInterrupts(base, (uint32_t)kI2C_GlobalInterruptEnable);
1118         }
1119     }
1120 
1121     return result;
1122 }
1123 
1124 /*!
1125  * brief Aborts an interrupt non-blocking transfer early.
1126  *
1127  * note This API can be called at any time when an interrupt non-blocking transfer initiates
1128  * to abort the transfer early.
1129  *
1130  * param base I2C base pointer.
1131  * param handle pointer to i2c_master_handle_t structure which stores the transfer state
1132  * retval kStatus_I2C_Timeout Timeout during polling flag.
1133  * retval kStatus_Success Successfully abort the transfer.
1134  */
I2C_MasterTransferAbort(I2C_Type * base,i2c_master_handle_t * handle)1135 status_t I2C_MasterTransferAbort(I2C_Type *base, i2c_master_handle_t *handle)
1136 {
1137     assert(handle != NULL);
1138 
1139     volatile uint8_t dummy = 0;
1140 
1141     /* Add this to avoid build warning. */
1142     dummy++;
1143 
1144     /* Disable interrupt. */
1145     I2C_DisableInterrupts(base, (uint32_t)kI2C_GlobalInterruptEnable);
1146 
1147     /* Reset the state to idle. */
1148     handle->state = (uint8_t)kIdleState;
1149 
1150     /* Send STOP signal. */
1151     if (handle->transfer.direction == kI2C_Read)
1152     {
1153         base->I2CR |= I2C_I2CR_TXAK_MASK;
1154 
1155         if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_IntPendingFlag) != kStatus_Success)
1156         {
1157             return kStatus_I2C_Timeout;
1158         }
1159         base->I2SR &= ~(uint16_t)kI2C_IntPendingFlag;
1160 
1161         base->I2CR &= ~((uint16_t)I2C_I2CR_MSTA_MASK | (uint16_t)I2C_I2CR_MTX_MASK | (uint16_t)I2C_I2CR_TXAK_MASK);
1162         dummy = (uint8_t)base->I2DR;
1163     }
1164     else
1165     {
1166         if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_IntPendingFlag) != kStatus_Success)
1167         {
1168             return kStatus_I2C_Timeout;
1169         }
1170         base->I2SR &= ~(uint16_t)kI2C_IntPendingFlag;
1171         base->I2CR &= ~((uint16_t)I2C_I2CR_MSTA_MASK | (uint16_t)I2C_I2CR_MTX_MASK | (uint16_t)I2C_I2CR_TXAK_MASK);
1172     }
1173     return kStatus_Success;
1174 }
1175 
1176 /*!
1177  * brief Gets the master transfer status during a interrupt non-blocking transfer.
1178  *
1179  * param base I2C base pointer.
1180  * param handle pointer to i2c_master_handle_t structure which stores the transfer state.
1181  * param count Number of bytes transferred so far by the non-blocking transaction.
1182  * retval kStatus_InvalidArgument count is Invalid.
1183  * retval kStatus_Success Successfully return the count.
1184  */
I2C_MasterTransferGetCount(I2C_Type * base,i2c_master_handle_t * handle,size_t * count)1185 status_t I2C_MasterTransferGetCount(I2C_Type *base, i2c_master_handle_t *handle, size_t *count)
1186 {
1187     assert(handle != NULL);
1188 
1189     if (NULL == count)
1190     {
1191         return kStatus_InvalidArgument;
1192     }
1193 
1194     *count = handle->transferSize - handle->transfer.dataSize;
1195 
1196     return kStatus_Success;
1197 }
1198 
1199 /*!
1200  * brief Master interrupt handler.
1201  *
1202  * param base I2C base pointer.
1203  * param i2cHandle pointer to i2c_master_handle_t structure.
1204  */
I2C_MasterTransferHandleIRQ(I2C_Type * base,void * i2cHandle)1205 void I2C_MasterTransferHandleIRQ(I2C_Type *base, void *i2cHandle)
1206 {
1207     assert(i2cHandle != NULL);
1208 
1209     i2c_master_handle_t *handle = (i2c_master_handle_t *)i2cHandle;
1210     status_t result             = kStatus_Success;
1211     bool isDone;
1212 
1213     /* Clear the interrupt flag. */
1214     base->I2SR &= ~(uint16_t)kI2C_IntPendingFlag;
1215 
1216     /* Check transfer complete flag. */
1217     result = I2C_MasterTransferRunStateMachine(base, handle, &isDone);
1218 
1219     if (isDone || (result != kStatus_Success))
1220     {
1221         /* Send stop command if transfer done or received Nak. */
1222         if ((0U == (handle->transfer.flags & (uint32_t)kI2C_TransferNoStopFlag)) || (result == kStatus_I2C_Nak) ||
1223             (result == kStatus_I2C_Addr_Nak))
1224         {
1225             /* Ensure stop command is a need. */
1226             if ((base->I2CR & I2C_I2CR_MSTA_MASK) != 0U)
1227             {
1228                 if (I2C_MasterStop(base) != kStatus_Success)
1229                 {
1230                     result = kStatus_I2C_Timeout;
1231                 }
1232             }
1233         }
1234 
1235         /* Restore handle to idle state. */
1236         handle->state = (uint8_t)kIdleState;
1237 
1238         /* Disable interrupt. */
1239         I2C_DisableInterrupts(base, (uint32_t)kI2C_GlobalInterruptEnable);
1240 
1241         /* Call the callback function after the function has completed. */
1242         if (handle->completionCallback != NULL)
1243         {
1244             handle->completionCallback(base, handle, result, handle->userData);
1245         }
1246     }
1247 }
1248 
1249 /*!
1250  * brief Initializes the I2C peripheral. Call this API to ungate the I2C clock
1251  * and initialize the I2C with the slave configuration.
1252  *
1253  * note This API should be called at the beginning of the application.
1254  * Otherwise, any operation to the I2C module can cause a hard fault
1255  * because the clock is not enabled. The configuration structure can partly be set
1256  * with default values by I2C_SlaveGetDefaultConfig() or it can be custom filled by the user.
1257  * This is an example.
1258  * code
1259  * i2c_slave_config_t config = {
1260  * .enableSlave = true,
1261  * .slaveAddress = 0x1DU,
1262  * };
1263  * I2C_SlaveInit(I2C0, &config);
1264  * endcode
1265  *
1266  * param base I2C base pointer
1267  * param slaveConfig A pointer to the slave configuration structure
1268  * param srcClock_Hz I2C peripheral clock frequency in Hz
1269  */
I2C_SlaveInit(I2C_Type * base,const i2c_slave_config_t * slaveConfig)1270 void I2C_SlaveInit(I2C_Type *base, const i2c_slave_config_t *slaveConfig)
1271 {
1272     assert(slaveConfig != NULL);
1273 
1274 #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
1275     /* Enable I2C clock. */
1276     CLOCK_EnableClock(s_i2cClocks[I2C_GetInstance(base)]);
1277 #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
1278 
1279     /* Reset the module. */
1280     base->IADR = 0;
1281     base->IFDR = 0;
1282     base->I2CR = 0;
1283     base->I2SR = 0;
1284 
1285     base->IADR = (uint16_t)((uint32_t)(slaveConfig->slaveAddress)) << 1U;
1286     base->I2CR = I2C_I2CR_IEN(slaveConfig->enableSlave);
1287 }
1288 
1289 /*!
1290  * brief De-initializes the I2C slave peripheral. Calling this API gates the I2C clock.
1291  * The I2C slave module can't work unless the I2C_SlaveInit is called to enable the clock.
1292  * param base I2C base pointer
1293  */
I2C_SlaveDeinit(I2C_Type * base)1294 void I2C_SlaveDeinit(I2C_Type *base)
1295 {
1296     /* Disable I2C module. */
1297     I2C_Enable(base, false);
1298 
1299 #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
1300     /* Disable I2C clock. */
1301     CLOCK_DisableClock(s_i2cClocks[I2C_GetInstance(base)]);
1302 #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
1303 }
1304 
1305 /*!
1306  * brief  Sets the I2C slave configuration structure to default values.
1307  *
1308  * The purpose of this API is to get the configuration structure initialized for use in the I2C_SlaveInit().
1309  * Modify fields of the structure before calling the I2C_SlaveInit().
1310  * This is an example.
1311  * code
1312  * i2c_slave_config_t config;
1313  * I2C_SlaveGetDefaultConfig(&config);
1314  * endcode
1315  * param slaveConfig A pointer to the slave configuration structure.
1316  */
I2C_SlaveGetDefaultConfig(i2c_slave_config_t * slaveConfig)1317 void I2C_SlaveGetDefaultConfig(i2c_slave_config_t *slaveConfig)
1318 {
1319     assert(slaveConfig != NULL);
1320 
1321     /* Initializes the configure structure to zero. */
1322     (void)memset(slaveConfig, 0, sizeof(*slaveConfig));
1323 
1324     /* Enable the I2C peripheral. */
1325     slaveConfig->enableSlave = true;
1326 }
1327 
1328 /*!
1329  * brief Performs a polling send transaction on the I2C bus.
1330  *
1331  * param base  The I2C peripheral base pointer.
1332  * param txBuff The pointer to the data to be transferred.
1333  * param txSize The length in bytes of the data to be transferred.
1334  * retval kStatus_Success Successfully complete the data transmission.
1335  * retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost.
1336  * retval kStataus_I2C_Nak Transfer error, receive NAK during transfer.
1337  */
I2C_SlaveWriteBlocking(I2C_Type * base,const uint8_t * txBuff,size_t txSize)1338 status_t I2C_SlaveWriteBlocking(I2C_Type *base, const uint8_t *txBuff, size_t txSize)
1339 {
1340     status_t result        = kStatus_Success;
1341     volatile uint8_t dummy = 0;
1342 
1343     /* Add this to avoid build warning. */
1344     dummy++;
1345 
1346     if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_AddressMatchFlag) != kStatus_Success)
1347     {
1348         return kStatus_I2C_Timeout;
1349     }
1350 
1351     /* Read dummy to release bus. */
1352     dummy = (uint8_t)base->I2DR;
1353 
1354     result = I2C_MasterWriteBlocking(base, txBuff, txSize, (uint32_t)kI2C_TransferDefaultFlag);
1355 
1356     /* Switch to receive mode. */
1357     base->I2CR &= ~((uint16_t)I2C_I2CR_MTX_MASK | (uint16_t)I2C_I2CR_TXAK_MASK);
1358 
1359     /* Read dummy to release bus. */
1360     dummy = (uint8_t)base->I2DR;
1361 
1362     return result;
1363 }
1364 
1365 /*!
1366  * brief Performs a polling receive transaction on the I2C bus.
1367  *
1368  * param base I2C peripheral base pointer.
1369  * param rxBuff The pointer to the data to store the received data.
1370  * param rxSize The length in bytes of the data to be received.
1371  */
I2C_SlaveReadBlocking(I2C_Type * base,uint8_t * rxBuff,size_t rxSize)1372 status_t I2C_SlaveReadBlocking(I2C_Type *base, uint8_t *rxBuff, size_t rxSize)
1373 {
1374     volatile uint8_t dummy = 0;
1375 
1376     /* Add this to avoid build warning. */
1377     dummy++;
1378 
1379     if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_AddressMatchFlag) != kStatus_Success)
1380     {
1381         return kStatus_I2C_Timeout;
1382     }
1383 
1384     /* Read dummy to release bus. */
1385     dummy = (uint8_t)base->I2DR;
1386 
1387     /* Clear the IICIF flag. */
1388     base->I2SR &= ~(uint16_t)kI2C_IntPendingFlag;
1389 
1390     /* Setup the I2C peripheral to receive data. */
1391     base->I2CR &= ~((uint16_t)I2C_I2CR_MTX_MASK);
1392 
1393     while (0U != rxSize--)
1394     {
1395         if (I2C_WaitForStatusReady(base, (uint8_t)kI2C_IntPendingFlag) != kStatus_Success)
1396         {
1397             return kStatus_I2C_Timeout;
1398         }
1399         /* Clear the IICIF flag. */
1400         base->I2SR &= ~(uint16_t)kI2C_IntPendingFlag;
1401 
1402         /* Read from the data register. */
1403         *rxBuff++ = (uint8_t)base->I2DR;
1404     }
1405     return kStatus_Success;
1406 }
1407 
1408 /*!
1409  * brief Initializes the I2C handle which is used in transactional functions.
1410  *
1411  * param base I2C base pointer.
1412  * param handle pointer to i2c_slave_handle_t structure to store the transfer state.
1413  * param callback pointer to user callback function.
1414  * param userData user parameter passed to the callback function.
1415  */
I2C_SlaveTransferCreateHandle(I2C_Type * base,i2c_slave_handle_t * handle,i2c_slave_transfer_callback_t callback,void * userData)1416 void I2C_SlaveTransferCreateHandle(I2C_Type *base,
1417                                    i2c_slave_handle_t *handle,
1418                                    i2c_slave_transfer_callback_t callback,
1419                                    void *userData)
1420 {
1421     assert(handle != NULL);
1422 
1423     uint32_t instance = I2C_GetInstance(base);
1424 
1425     /* Zero handle. */
1426     (void)memset(handle, 0, sizeof(*handle));
1427 
1428     /* Set callback and userData. */
1429     handle->callback = callback;
1430     handle->userData = userData;
1431 
1432     /* Save the context in global variables to support the double weak mechanism. */
1433     s_i2cHandle[instance] = handle;
1434 
1435     /* Save slave interrupt handler. */
1436     s_i2cSlaveIsr = I2C_SlaveTransferHandleIRQ;
1437 
1438     /* Enable NVIC interrupt. */
1439     (void)EnableIRQ(s_i2cIrqs[instance]);
1440 }
1441 
1442 /*!
1443  * brief Starts accepting slave transfers.
1444  *
1445  * Call this API after calling the I2C_SlaveInit() and I2C_SlaveTransferCreateHandle() to start processing
1446  * transactions driven by an I2C master. The slave monitors the I2C bus and passes events to the
1447  * callback that was passed into the call to I2C_SlaveTransferCreateHandle(). The callback is always invoked
1448  * from the interrupt context.
1449  *
1450  * The set of events received by the callback is customizable. To do so, set the a eventMask parameter to
1451  * the OR'd combination of #i2c_slave_transfer_event_t enumerators for the events you wish to receive.
1452  * The #kI2C_SlaveTransmitEvent and #kLPI2C_SlaveReceiveEvent events are always enabled and do not need
1453  * to be included in the mask. Alternatively, pass 0 to get a default set of only the transmit and
1454  * receive events that are always enabled. In addition, the #kI2C_SlaveAllEvents constant is provided as
1455  * a convenient way to enable all events.
1456  *
1457  * param base The I2C peripheral base address.
1458  * param handle Pointer to #i2c_slave_handle_t structure which stores the transfer state.
1459  * param eventMask Bit mask formed by OR'ing together #i2c_slave_transfer_event_t enumerators to specify
1460  *      which events to send to the callback. Other accepted values are 0 to get a default set of
1461  *      only the transmit and receive events, and #kI2C_SlaveAllEvents to enable all events.
1462  *
1463  * retval #kStatus_Success Slave transfers were successfully started.
1464  * retval #kStatus_I2C_Busy Slave transfers have already been started on this handle.
1465  */
I2C_SlaveTransferNonBlocking(I2C_Type * base,i2c_slave_handle_t * handle,uint32_t eventMask)1466 status_t I2C_SlaveTransferNonBlocking(I2C_Type *base, i2c_slave_handle_t *handle, uint32_t eventMask)
1467 {
1468     assert(handle != NULL);
1469 
1470     /* Check if the I2C bus is idle - if not return busy status. */
1471     if (handle->state != (uint8_t)kIdleState)
1472     {
1473         return kStatus_I2C_Busy;
1474     }
1475     else
1476     {
1477         /* Disable LPI2C IRQ sources while we configure stuff. */
1478         (void)I2C_DisableInterrupts(base, (uint32_t)kIrqFlags);
1479 
1480         /* Clear transfer in handle. */
1481         (void)memset(&handle->transfer, 0, sizeof(handle->transfer));
1482 
1483         /* Record that we're busy. */
1484         handle->state = (uint8_t)kCheckAddressState;
1485 
1486         /* Set up event mask. tx and rx are always enabled. */
1487         handle->eventMask = eventMask | (uint32_t)kI2C_SlaveTransmitEvent | (uint32_t)kI2C_SlaveReceiveEvent;
1488 
1489         /* Clear all flags. */
1490         I2C_SlaveClearStatusFlags(base, (uint32_t)kClearFlags);
1491 
1492         /* Enable I2C internal IRQ sources. NVIC IRQ was enabled in CreateHandle() */
1493         I2C_EnableInterrupts(base, (uint32_t)kIrqFlags);
1494     }
1495 
1496     return kStatus_Success;
1497 }
1498 
1499 /*!
1500  * brief Aborts the slave transfer.
1501  *
1502  * note This API can be called at any time to stop slave for handling the bus events.
1503  *
1504  * param base I2C base pointer.
1505  * param handle pointer to i2c_slave_handle_t structure which stores the transfer state.
1506  */
I2C_SlaveTransferAbort(I2C_Type * base,i2c_slave_handle_t * handle)1507 void I2C_SlaveTransferAbort(I2C_Type *base, i2c_slave_handle_t *handle)
1508 {
1509     assert(handle != NULL);
1510 
1511     if (handle->state != (uint8_t)kIdleState)
1512     {
1513         /* Disable interrupts. */
1514         I2C_DisableInterrupts(base, (uint32_t)kIrqFlags);
1515 
1516         /* Reset transfer info. */
1517         (void)memset(&handle->transfer, 0, sizeof(handle->transfer));
1518 
1519         /* Reset the state to idle. */
1520         handle->state = (uint8_t)kIdleState;
1521     }
1522 }
1523 
1524 /*!
1525  * brief Gets the slave transfer remaining bytes during a interrupt non-blocking transfer.
1526  *
1527  * param base I2C base pointer.
1528  * param handle pointer to i2c_slave_handle_t structure.
1529  * param count Number of bytes transferred so far by the non-blocking transaction.
1530  * retval kStatus_InvalidArgument count is Invalid.
1531  * retval kStatus_Success Successfully return the count.
1532  */
I2C_SlaveTransferGetCount(I2C_Type * base,i2c_slave_handle_t * handle,size_t * count)1533 status_t I2C_SlaveTransferGetCount(I2C_Type *base, i2c_slave_handle_t *handle, size_t *count)
1534 {
1535     assert(handle != NULL);
1536 
1537     if (NULL == count)
1538     {
1539         return kStatus_InvalidArgument;
1540     }
1541 
1542     /* Catch when there is not an active transfer. */
1543     if (handle->state == (uint8_t)kIdleState)
1544     {
1545         *count = 0;
1546         return kStatus_NoTransferInProgress;
1547     }
1548 
1549     /* For an active transfer, just return the count from the handle. */
1550     *count = handle->transfer.transferredCount;
1551 
1552     return kStatus_Success;
1553 }
1554 
1555 /*!
1556  * brief Slave interrupt handler.
1557  *
1558  * param base I2C base pointer.
1559  * param i2cHandle pointer to i2c_slave_handle_t structure which stores the transfer state
1560  */
I2C_SlaveTransferHandleIRQ(I2C_Type * base,void * i2cHandle)1561 void I2C_SlaveTransferHandleIRQ(I2C_Type *base, void *i2cHandle)
1562 {
1563     assert(i2cHandle != NULL);
1564 
1565     uint32_t status;
1566     bool doTransmit            = false;
1567     i2c_slave_handle_t *handle = (i2c_slave_handle_t *)i2cHandle;
1568     i2c_slave_transfer_t *xfer;
1569     volatile uint8_t dummy = 0;
1570 
1571     /* Add this to avoid build warning. */
1572     dummy++;
1573 
1574     status = I2C_SlaveGetStatusFlags(base);
1575     xfer   = &(handle->transfer);
1576 
1577     /* Clear the interrupt flag. */
1578     base->I2SR &= ~(uint16_t)kI2C_IntPendingFlag;
1579 
1580     /* Check NAK */
1581     if ((status & (uint32_t)kI2C_ReceiveNakFlag) != 0U)
1582     {
1583         /* Set receive mode. */
1584         base->I2CR &= ~((uint16_t)I2C_I2CR_MTX_MASK | (uint16_t)I2C_I2CR_TXAK_MASK);
1585 
1586         /* Read dummy. */
1587         dummy = (uint8_t)base->I2DR;
1588 
1589         if (handle->transfer.dataSize != 0U)
1590         {
1591             xfer->event            = kI2C_SlaveCompletionEvent;
1592             xfer->completionStatus = kStatus_I2C_Nak;
1593             handle->state          = (uint8_t)kIdleState;
1594 
1595             if (((handle->eventMask & (uint32_t)xfer->event) != 0U) && (handle->callback != NULL))
1596             {
1597                 handle->callback(base, xfer, handle->userData);
1598             }
1599         }
1600         else
1601         {
1602             xfer->event            = kI2C_SlaveCompletionEvent;
1603             xfer->completionStatus = kStatus_Success;
1604             handle->state          = (uint8_t)kIdleState;
1605 
1606             if (((handle->eventMask & (uint32_t)xfer->event) != 0U) && (handle->callback != NULL))
1607             {
1608                 handle->callback(base, xfer, handle->userData);
1609             }
1610         }
1611     }
1612     /* Check address match. */
1613     else if ((status & (uint32_t)kI2C_AddressMatchFlag) != 0U)
1614     {
1615         xfer->event = kI2C_SlaveAddressMatchEvent;
1616 
1617         /* Slave transmit, master reading from slave. */
1618         if ((status & (uint32_t)kI2C_TransferDirectionFlag) != 0U)
1619         {
1620             handle->state = (uint8_t)kSendDataState;
1621             /* Change direction to send data. */
1622             base->I2CR |= I2C_I2CR_MTX_MASK;
1623 
1624             doTransmit = true;
1625         }
1626         else
1627         {
1628             handle->state = (uint8_t)kReceiveDataState;
1629             /* Slave receive, master writing to slave. */
1630             base->I2CR &= ~((uint16_t)I2C_I2CR_MTX_MASK | (uint16_t)I2C_I2CR_TXAK_MASK);
1631 
1632             /* Read dummy to release the bus. */
1633             dummy = (uint8_t)base->I2DR;
1634         }
1635 
1636         if (((handle->eventMask & (uint32_t)xfer->event) != 0U) && (handle->callback != NULL))
1637         {
1638             handle->callback(base, xfer, handle->userData);
1639         }
1640     }
1641     /* Check transfer complete flag. */
1642     else if ((status & (uint32_t)kI2C_TransferCompleteFlag) != 0U)
1643     {
1644         /* Slave transmit, master reading from slave. */
1645         if (handle->state == (uint8_t)kSendDataState)
1646         {
1647             doTransmit = true;
1648         }
1649         else
1650         {
1651             /* If we're out of data, invoke callback to get more. */
1652             if ((NULL == xfer->data) || (0U == xfer->dataSize))
1653             {
1654                 xfer->event = kI2C_SlaveReceiveEvent;
1655 
1656                 if (handle->callback != NULL)
1657                 {
1658                     handle->callback(base, xfer, handle->userData);
1659                 }
1660 
1661                 /* Clear the transferred count now that we have a new buffer. */
1662                 xfer->transferredCount = 0;
1663             }
1664 
1665             /* Slave receive, master writing to slave. */
1666             uint8_t data = (uint8_t)base->I2DR;
1667 
1668             if (handle->transfer.dataSize != 0U)
1669             {
1670                 /* Receive data. */
1671                 *handle->transfer.data++ = data;
1672                 handle->transfer.dataSize--;
1673                 xfer->transferredCount++;
1674 
1675                 if (0U == handle->transfer.dataSize)
1676                 {
1677                     xfer->event            = kI2C_SlaveCompletionEvent;
1678                     xfer->completionStatus = kStatus_Success;
1679                     handle->state          = (uint8_t)kIdleState;
1680 
1681                     /* Proceed receive complete event. */
1682                     if (((handle->eventMask & (uint32_t)xfer->event) != 0U) && (handle->callback != NULL))
1683                     {
1684                         handle->callback(base, xfer, handle->userData);
1685                     }
1686                 }
1687             }
1688         }
1689     }
1690     else
1691     {
1692         /* Read dummy to release bus. */
1693         dummy = (uint8_t)base->I2DR;
1694     }
1695 
1696     /* Send data if there is the need. */
1697     if (doTransmit)
1698     {
1699         /* If we're out of data, invoke callback to get more. */
1700         if ((NULL == xfer->data) || (0U == xfer->dataSize))
1701         {
1702             xfer->event = kI2C_SlaveTransmitEvent;
1703 
1704             if (handle->callback != NULL)
1705             {
1706                 handle->callback(base, xfer, handle->userData);
1707             }
1708 
1709             /* Clear the transferred count now that we have a new buffer. */
1710             xfer->transferredCount = 0;
1711         }
1712 
1713         if (handle->transfer.dataSize != 0U)
1714         {
1715             /* Send data. */
1716             base->I2DR = *handle->transfer.data++;
1717             handle->transfer.dataSize--;
1718             xfer->transferredCount++;
1719         }
1720         else
1721         {
1722             /* Switch to receive mode. */
1723             base->I2CR &= ~((uint16_t)I2C_I2CR_MTX_MASK | (uint16_t)I2C_I2CR_TXAK_MASK);
1724 
1725             /* Read dummy to release bus. */
1726             dummy = (uint8_t)base->I2DR;
1727 
1728             xfer->event            = kI2C_SlaveCompletionEvent;
1729             xfer->completionStatus = kStatus_Success;
1730             handle->state          = (uint8_t)kIdleState;
1731 
1732             /* Proceed txdone event. */
1733             if (((handle->eventMask & (uint32_t)xfer->event) != 0U) && (handle->callback != NULL))
1734             {
1735                 handle->callback(base, xfer, handle->userData);
1736             }
1737         }
1738     }
1739 }
1740 
1741 #if defined(I2C1)
1742 void I2C1_DriverIRQHandler(void);
I2C1_DriverIRQHandler(void)1743 void I2C1_DriverIRQHandler(void)
1744 {
1745     I2C_TransferCommonIRQHandler(I2C1, s_i2cHandle[1]);
1746 }
1747 #endif
1748 
1749 #if defined(I2C2)
1750 void I2C2_DriverIRQHandler(void);
I2C2_DriverIRQHandler(void)1751 void I2C2_DriverIRQHandler(void)
1752 {
1753     I2C_TransferCommonIRQHandler(I2C2, s_i2cHandle[2]);
1754 }
1755 #endif
1756 
1757 #if defined(I2C3)
1758 void I2C3_DriverIRQHandler(void);
I2C3_DriverIRQHandler(void)1759 void I2C3_DriverIRQHandler(void)
1760 {
1761     I2C_TransferCommonIRQHandler(I2C3, s_i2cHandle[3]);
1762 }
1763 #endif
1764 
1765 #if defined(I2C4)
1766 void I2C4_DriverIRQHandler(void);
I2C4_DriverIRQHandler(void)1767 void I2C4_DriverIRQHandler(void)
1768 {
1769     I2C_TransferCommonIRQHandler(I2C4, s_i2cHandle[4]);
1770 }
1771 #endif
1772 
1773 #if defined(I2C5)
1774 void I2C5_DriverIRQHandler(void);
I2C5_DriverIRQHandler(void)1775 void I2C5_DriverIRQHandler(void)
1776 {
1777     I2C_TransferCommonIRQHandler(I2C5, s_i2cHandle[5]);
1778 }
1779 #endif
1780 
1781 #if defined(I2C6)
1782 void I2C6_DriverIRQHandler(void);
I2C6_DriverIRQHandler(void)1783 void I2C6_DriverIRQHandler(void)
1784 {
1785     I2C_TransferCommonIRQHandler(I2C6, s_i2cHandle[6]);
1786 }
1787 #endif
1788