You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

2424 line
75 KiB

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