fsl_i2c.c 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  1. /*
  2. * Copyright (c) 2016, Freescale Semiconductor, Inc.
  3. * Copyright 2016-2017 NXP
  4. *
  5. * Redistribution and use in source and binary forms, with or without modification,
  6. * are permitted provided that the following conditions are met:
  7. *
  8. * o Redistributions of source code must retain the above copyright notice, this list
  9. * of conditions and the following disclaimer.
  10. *
  11. * o Redistributions in binary form must reproduce the above copyright notice, this
  12. * list of conditions and the following disclaimer in the documentation and/or
  13. * other materials provided with the distribution.
  14. *
  15. * o Neither the name of the copyright holder nor the names of its
  16. * contributors may be used to endorse or promote products derived from this
  17. * software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  20. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  21. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  23. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  24. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  25. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  26. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  28. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #include "fsl_i2c.h"
  31. #include "fsl_flexcomm.h"
  32. #include <stdlib.h>
  33. #include <string.h>
  34. /*******************************************************************************
  35. * Definitions
  36. ******************************************************************************/
  37. /*! @brief Common sets of flags used by the driver. */
  38. enum _i2c_flag_constants
  39. {
  40. kI2C_MasterIrqFlags = I2C_INTSTAT_MSTPENDING_MASK | I2C_INTSTAT_MSTARBLOSS_MASK | I2C_INTSTAT_MSTSTSTPERR_MASK,
  41. kI2C_SlaveIrqFlags = I2C_INTSTAT_SLVPENDING_MASK | I2C_INTSTAT_SLVDESEL_MASK,
  42. };
  43. /*******************************************************************************
  44. * Prototypes
  45. ******************************************************************************/
  46. static status_t I2C_InitTransferStateMachine(I2C_Type *base, i2c_master_handle_t *handle, i2c_master_transfer_t *xfer);
  47. static void I2C_SlaveInternalStateMachineReset(I2C_Type *base);
  48. static status_t I2C_SlaveDivVal(uint32_t srcClock_Hz, i2c_slave_bus_speed_t busSpeed, uint32_t *divVal);
  49. static uint32_t I2C_SlavePollPending(I2C_Type *base);
  50. static void I2C_SlaveInvokeEvent(I2C_Type *base, i2c_slave_handle_t *handle, i2c_slave_transfer_event_t event);
  51. static bool I2C_SlaveAddressIRQ(I2C_Type *base, i2c_slave_handle_t *handle);
  52. static status_t I2C_SlaveTransferNonBlockingInternal(I2C_Type *base,
  53. i2c_slave_handle_t *handle,
  54. const void *txData,
  55. size_t txSize,
  56. void *rxData,
  57. size_t rxSize,
  58. uint32_t eventMask);
  59. /*******************************************************************************
  60. * Variables
  61. ******************************************************************************/
  62. /*! @brief Array to map i2c instance number to base address. */
  63. static const uint32_t s_i2cBaseAddrs[FSL_FEATURE_SOC_I2C_COUNT] = I2C_BASE_ADDRS;
  64. /*! @brief IRQ name array */
  65. static const IRQn_Type s_i2cIRQ[] = I2C_IRQS;
  66. /*******************************************************************************
  67. * Code
  68. ******************************************************************************/
  69. /*!
  70. * @brief Returns an instance number given a base address.
  71. *
  72. * If an invalid base address is passed, debug builds will assert. Release builds will just return
  73. * instance number 0.
  74. *
  75. * @param base The I2C peripheral base address.
  76. * @return I2C instance number starting from 0.
  77. */
  78. uint32_t I2C_GetInstance(I2C_Type *base)
  79. {
  80. int i;
  81. for (i = 0; i < FSL_FEATURE_SOC_I2C_COUNT; i++)
  82. {
  83. if ((uint32_t)base == s_i2cBaseAddrs[i])
  84. {
  85. return i;
  86. }
  87. }
  88. assert(false);
  89. return 0;
  90. }
  91. void I2C_MasterGetDefaultConfig(i2c_master_config_t *masterConfig)
  92. {
  93. masterConfig->enableMaster = true;
  94. masterConfig->baudRate_Bps = 100000U;
  95. masterConfig->enableTimeout = false;
  96. }
  97. void I2C_MasterInit(I2C_Type *base, const i2c_master_config_t *masterConfig, uint32_t srcClock_Hz)
  98. {
  99. FLEXCOMM_Init(base, FLEXCOMM_PERIPH_I2C);
  100. I2C_MasterEnable(base, masterConfig->enableMaster);
  101. I2C_MasterSetBaudRate(base, masterConfig->baudRate_Bps, srcClock_Hz);
  102. }
  103. void I2C_MasterDeinit(I2C_Type *base)
  104. {
  105. I2C_MasterEnable(base, false);
  106. }
  107. void I2C_MasterSetBaudRate(I2C_Type *base, uint32_t baudRate_Bps, uint32_t srcClock_Hz)
  108. {
  109. uint32_t scl, divider;
  110. uint32_t best_scl, best_div;
  111. uint32_t err, best_err;
  112. best_err = 0;
  113. for (scl = 9; scl >= 2; scl--)
  114. {
  115. /* calculated ideal divider value for given scl */
  116. divider = srcClock_Hz / (baudRate_Bps * scl * 2u);
  117. /* adjust it if it is out of range */
  118. divider = (divider > 0x10000u) ? 0x10000 : divider;
  119. /* calculate error */
  120. err = srcClock_Hz - (baudRate_Bps * scl * 2u * divider);
  121. if ((err < best_err) || (best_err == 0))
  122. {
  123. best_div = divider;
  124. best_scl = scl;
  125. best_err = err;
  126. }
  127. if ((err == 0) || (divider >= 0x10000u))
  128. {
  129. /* either exact value was found
  130. or divider is at its max (it would even greater in the next iteration for sure) */
  131. break;
  132. }
  133. }
  134. base->CLKDIV = I2C_CLKDIV_DIVVAL(best_div - 1);
  135. base->MSTTIME = I2C_MSTTIME_MSTSCLLOW(best_scl - 2u) | I2C_MSTTIME_MSTSCLHIGH(best_scl - 2u);
  136. }
  137. static uint32_t I2C_PendingStatusWait(I2C_Type *base)
  138. {
  139. uint32_t status;
  140. do
  141. {
  142. status = I2C_GetStatusFlags(base);
  143. } while ((status & I2C_STAT_MSTPENDING_MASK) == 0);
  144. /* Clear controller state. */
  145. I2C_MasterClearStatusFlags(base, I2C_STAT_MSTARBLOSS_MASK | I2C_STAT_MSTSTSTPERR_MASK);
  146. return status;
  147. }
  148. status_t I2C_MasterStart(I2C_Type *base, uint8_t address, i2c_direction_t direction)
  149. {
  150. I2C_PendingStatusWait(base);
  151. /* Write Address and RW bit to data register */
  152. base->MSTDAT = ((uint32_t)address << 1) | ((uint32_t)direction & 1u);
  153. /* Start the transfer */
  154. base->MSTCTL = I2C_MSTCTL_MSTSTART_MASK;
  155. return kStatus_Success;
  156. }
  157. status_t I2C_MasterStop(I2C_Type *base)
  158. {
  159. I2C_PendingStatusWait(base);
  160. base->MSTCTL = I2C_MSTCTL_MSTSTOP_MASK;
  161. return kStatus_Success;
  162. }
  163. status_t I2C_MasterWriteBlocking(I2C_Type *base, const void *txBuff, size_t txSize, uint32_t flags)
  164. {
  165. uint32_t status;
  166. uint32_t master_state;
  167. status_t err;
  168. const uint8_t *buf = (const uint8_t *)(uintptr_t)txBuff;
  169. assert(txBuff);
  170. err = kStatus_Success;
  171. while (txSize)
  172. {
  173. status = I2C_PendingStatusWait(base);
  174. if (status & I2C_STAT_MSTARBLOSS_MASK)
  175. {
  176. return kStatus_I2C_ArbitrationLost;
  177. }
  178. if (status & I2C_STAT_MSTSTSTPERR_MASK)
  179. {
  180. return kStatus_I2C_StartStopError;
  181. }
  182. master_state = (status & I2C_STAT_MSTSTATE_MASK) >> I2C_STAT_MSTSTATE_SHIFT;
  183. switch (master_state)
  184. {
  185. case I2C_STAT_MSTCODE_TXREADY:
  186. /* ready to send next byte */
  187. base->MSTDAT = *buf++;
  188. txSize--;
  189. base->MSTCTL = I2C_MSTCTL_MSTCONTINUE_MASK;
  190. break;
  191. case I2C_STAT_MSTCODE_NACKADR:
  192. case I2C_STAT_MSTCODE_NACKDAT:
  193. /* slave nacked the last byte */
  194. err = kStatus_I2C_Nak;
  195. break;
  196. default:
  197. /* unexpected state */
  198. err = kStatus_I2C_UnexpectedState;
  199. break;
  200. }
  201. if (err != kStatus_Success)
  202. {
  203. return err;
  204. }
  205. }
  206. status = I2C_PendingStatusWait(base);
  207. if ((status & (I2C_STAT_MSTARBLOSS_MASK | I2C_STAT_MSTSTSTPERR_MASK)) == 0)
  208. {
  209. if (!(flags & kI2C_TransferNoStopFlag))
  210. {
  211. /* Initiate stop */
  212. base->MSTCTL = I2C_MSTCTL_MSTSTOP_MASK;
  213. status = I2C_PendingStatusWait(base);
  214. }
  215. }
  216. if (status & I2C_STAT_MSTARBLOSS_MASK)
  217. {
  218. return kStatus_I2C_ArbitrationLost;
  219. }
  220. if (status & I2C_STAT_MSTSTSTPERR_MASK)
  221. {
  222. return kStatus_I2C_StartStopError;
  223. }
  224. return kStatus_Success;
  225. }
  226. status_t I2C_MasterReadBlocking(I2C_Type *base, void *rxBuff, size_t rxSize, uint32_t flags)
  227. {
  228. uint32_t status = 0;
  229. uint32_t master_state;
  230. status_t err;
  231. uint8_t *buf = (uint8_t *)(rxBuff);
  232. assert(rxBuff);
  233. err = kStatus_Success;
  234. while (rxSize)
  235. {
  236. status = I2C_PendingStatusWait(base);
  237. if (status & (I2C_STAT_MSTARBLOSS_MASK | I2C_STAT_MSTSTSTPERR_MASK))
  238. {
  239. break;
  240. }
  241. master_state = (status & I2C_STAT_MSTSTATE_MASK) >> I2C_STAT_MSTSTATE_SHIFT;
  242. switch (master_state)
  243. {
  244. case I2C_STAT_MSTCODE_RXREADY:
  245. /* ready to send next byte */
  246. *(buf++) = base->MSTDAT;
  247. if (--rxSize)
  248. {
  249. base->MSTCTL = I2C_MSTCTL_MSTCONTINUE_MASK;
  250. }
  251. else
  252. {
  253. if ((flags & kI2C_TransferNoStopFlag) == 0)
  254. {
  255. /* initiate NAK and stop */
  256. base->MSTCTL = I2C_MSTCTL_MSTSTOP_MASK;
  257. status = I2C_PendingStatusWait(base);
  258. }
  259. }
  260. break;
  261. case I2C_STAT_MSTCODE_NACKADR:
  262. case I2C_STAT_MSTCODE_NACKDAT:
  263. /* slave nacked the last byte */
  264. err = kStatus_I2C_Nak;
  265. break;
  266. default:
  267. /* unexpected state */
  268. err = kStatus_I2C_UnexpectedState;
  269. break;
  270. }
  271. if (err != kStatus_Success)
  272. {
  273. return err;
  274. }
  275. }
  276. if (status & I2C_STAT_MSTARBLOSS_MASK)
  277. {
  278. return kStatus_I2C_ArbitrationLost;
  279. }
  280. if (status & I2C_STAT_MSTSTSTPERR_MASK)
  281. {
  282. return kStatus_I2C_StartStopError;
  283. }
  284. return kStatus_Success;
  285. }
  286. status_t I2C_MasterTransferBlocking(I2C_Type *base, i2c_master_transfer_t *xfer)
  287. {
  288. status_t result = kStatus_Success;
  289. uint32_t subaddress;
  290. uint8_t subaddrBuf[4];
  291. int i;
  292. assert(xfer);
  293. /* If repeated start is requested, send repeated start. */
  294. if (!(xfer->flags & kI2C_TransferNoStartFlag))
  295. {
  296. if (xfer->subaddressSize)
  297. {
  298. result = I2C_MasterStart(base, xfer->slaveAddress, kI2C_Write);
  299. if (result == kStatus_Success)
  300. {
  301. /* Prepare subaddress transmit buffer, most significant byte is stored at the lowest address */
  302. subaddress = xfer->subaddress;
  303. for (i = xfer->subaddressSize - 1; i >= 0; i--)
  304. {
  305. subaddrBuf[i] = subaddress & 0xff;
  306. subaddress >>= 8;
  307. }
  308. /* Send subaddress. */
  309. result = I2C_MasterWriteBlocking(base, subaddrBuf, xfer->subaddressSize, kI2C_TransferNoStopFlag);
  310. if ((result == kStatus_Success) && (xfer->direction == kI2C_Read))
  311. {
  312. result = I2C_MasterRepeatedStart(base, xfer->slaveAddress, xfer->direction);
  313. }
  314. }
  315. }
  316. else if (xfer->flags & kI2C_TransferRepeatedStartFlag)
  317. {
  318. result = I2C_MasterRepeatedStart(base, xfer->slaveAddress, xfer->direction);
  319. }
  320. else
  321. {
  322. result = I2C_MasterStart(base, xfer->slaveAddress, xfer->direction);
  323. }
  324. }
  325. if (result == kStatus_Success)
  326. {
  327. if ((xfer->direction == kI2C_Write) && (xfer->dataSize > 0))
  328. {
  329. /* Transmit data. */
  330. result = I2C_MasterWriteBlocking(base, xfer->data, xfer->dataSize, xfer->flags);
  331. }
  332. else
  333. {
  334. if ((xfer->direction == kI2C_Read) && (xfer->dataSize > 0))
  335. {
  336. /* Receive Data. */
  337. result = I2C_MasterReadBlocking(base, xfer->data, xfer->dataSize, xfer->flags);
  338. }
  339. }
  340. }
  341. if (result == kStatus_I2C_Nak)
  342. {
  343. I2C_MasterStop(base);
  344. }
  345. return result;
  346. }
  347. void I2C_MasterTransferCreateHandle(I2C_Type *base,
  348. i2c_master_handle_t *handle,
  349. i2c_master_transfer_callback_t callback,
  350. void *userData)
  351. {
  352. uint32_t instance;
  353. assert(handle);
  354. /* Clear out the handle. */
  355. memset(handle, 0, sizeof(*handle));
  356. /* Look up instance number */
  357. instance = I2C_GetInstance(base);
  358. /* Save base and instance. */
  359. handle->completionCallback = callback;
  360. handle->userData = userData;
  361. FLEXCOMM_SetIRQHandler(base, (flexcomm_irq_handler_t)(uintptr_t)I2C_MasterTransferHandleIRQ, handle);
  362. /* Clear internal IRQ enables and enable NVIC IRQ. */
  363. I2C_DisableInterrupts(base, kI2C_MasterIrqFlags);
  364. EnableIRQ(s_i2cIRQ[instance]);
  365. }
  366. status_t I2C_MasterTransferNonBlocking(I2C_Type *base, i2c_master_handle_t *handle, i2c_master_transfer_t *xfer)
  367. {
  368. status_t result;
  369. assert(handle);
  370. assert(xfer);
  371. assert(xfer->subaddressSize <= sizeof(xfer->subaddress));
  372. /* Return busy if another transaction is in progress. */
  373. if (handle->state != kIdleState)
  374. {
  375. return kStatus_I2C_Busy;
  376. }
  377. /* Disable I2C IRQ sources while we configure stuff. */
  378. I2C_DisableInterrupts(base, kI2C_MasterIrqFlags);
  379. /* Prepare transfer state machine. */
  380. result = I2C_InitTransferStateMachine(base, handle, xfer);
  381. /* Clear error flags. */
  382. I2C_MasterClearStatusFlags(base, I2C_STAT_MSTARBLOSS_MASK | I2C_STAT_MSTSTSTPERR_MASK);
  383. /* Enable I2C internal IRQ sources. */
  384. I2C_EnableInterrupts(base, kI2C_MasterIrqFlags);
  385. return result;
  386. }
  387. status_t I2C_MasterTransferGetCount(I2C_Type *base, i2c_master_handle_t *handle, size_t *count)
  388. {
  389. assert(handle);
  390. if (!count)
  391. {
  392. return kStatus_InvalidArgument;
  393. }
  394. /* Catch when there is not an active transfer. */
  395. if (handle->state == kIdleState)
  396. {
  397. *count = 0;
  398. return kStatus_NoTransferInProgress;
  399. }
  400. /* There is no necessity to disable interrupts as we read a single integer value */
  401. *count = handle->transferCount;
  402. return kStatus_Success;
  403. }
  404. void I2C_MasterTransferAbort(I2C_Type *base, i2c_master_handle_t *handle)
  405. {
  406. uint32_t status;
  407. uint32_t master_state;
  408. if (handle->state != kIdleState)
  409. {
  410. /* Disable internal IRQ enables. */
  411. I2C_DisableInterrupts(base, kI2C_MasterIrqFlags);
  412. /* Wait until module is ready */
  413. status = I2C_PendingStatusWait(base);
  414. /* Get the state of the I2C module */
  415. master_state = (status & I2C_STAT_MSTSTATE_MASK) >> I2C_STAT_MSTSTATE_SHIFT;
  416. if (master_state != I2C_STAT_MSTCODE_IDLE)
  417. {
  418. /* Send a stop command to finalize the transfer. */
  419. base->MSTCTL = I2C_MSTCTL_MSTSTOP_MASK;
  420. /* Wait until the STOP is completed */
  421. I2C_PendingStatusWait(base);
  422. }
  423. /* Reset handle. */
  424. handle->state = kIdleState;
  425. }
  426. }
  427. /*!
  428. * @brief Prepares the transfer state machine and fills in the command buffer.
  429. * @param handle Master nonblocking driver handle.
  430. */
  431. static status_t I2C_InitTransferStateMachine(I2C_Type *base, i2c_master_handle_t *handle, i2c_master_transfer_t *xfer)
  432. {
  433. struct _i2c_master_transfer *transfer;
  434. handle->transfer = *xfer;
  435. transfer = &(handle->transfer);
  436. handle->transferCount = 0;
  437. handle->remainingBytes = transfer->dataSize;
  438. handle->buf = (uint8_t *)transfer->data;
  439. handle->remainingSubaddr = 0;
  440. if (transfer->flags & kI2C_TransferNoStartFlag)
  441. {
  442. /* Start condition shall be ommited, switch directly to next phase */
  443. if (transfer->dataSize == 0)
  444. {
  445. handle->state = kStopState;
  446. }
  447. else if (handle->transfer.direction == kI2C_Write)
  448. {
  449. handle->state = kTransmitDataState;
  450. }
  451. else if (handle->transfer.direction == kI2C_Read)
  452. {
  453. handle->state = kReceiveDataState;
  454. }
  455. else
  456. {
  457. return kStatus_I2C_InvalidParameter;
  458. }
  459. }
  460. else
  461. {
  462. if (transfer->subaddressSize != 0)
  463. {
  464. int i;
  465. uint32_t subaddress;
  466. if (transfer->subaddressSize > sizeof(handle->subaddrBuf))
  467. {
  468. return kStatus_I2C_InvalidParameter;
  469. }
  470. /* Prepare subaddress transmit buffer, most significant byte is stored at the lowest address */
  471. subaddress = xfer->subaddress;
  472. for (i = xfer->subaddressSize - 1; i >= 0; i--)
  473. {
  474. handle->subaddrBuf[i] = subaddress & 0xff;
  475. subaddress >>= 8;
  476. }
  477. handle->remainingSubaddr = transfer->subaddressSize;
  478. }
  479. handle->state = kStartState;
  480. }
  481. return kStatus_Success;
  482. }
  483. /*!
  484. * @brief Execute states until FIFOs are exhausted.
  485. * @param handle Master nonblocking driver handle.
  486. * @param[out] isDone Set to true if the transfer has completed.
  487. * @retval #kStatus_Success
  488. * @retval #kStatus_I2C_ArbitrationLost
  489. * @retval #kStatus_I2C_Nak
  490. */
  491. static status_t I2C_RunTransferStateMachine(I2C_Type *base, i2c_master_handle_t *handle, bool *isDone)
  492. {
  493. uint32_t status;
  494. uint32_t master_state;
  495. struct _i2c_master_transfer *transfer;
  496. status_t err;
  497. transfer = &(handle->transfer);
  498. *isDone = false;
  499. status = I2C_GetStatusFlags(base);
  500. if (status & I2C_STAT_MSTARBLOSS_MASK)
  501. {
  502. I2C_MasterClearStatusFlags(base, I2C_STAT_MSTARBLOSS_MASK);
  503. return kStatus_I2C_ArbitrationLost;
  504. }
  505. if (status & I2C_STAT_MSTSTSTPERR_MASK)
  506. {
  507. I2C_MasterClearStatusFlags(base, I2C_STAT_MSTSTSTPERR_MASK);
  508. return kStatus_I2C_StartStopError;
  509. }
  510. if ((status & I2C_STAT_MSTPENDING_MASK) == 0)
  511. {
  512. return kStatus_I2C_Busy;
  513. }
  514. /* Get the state of the I2C module */
  515. master_state = (status & I2C_STAT_MSTSTATE_MASK) >> I2C_STAT_MSTSTATE_SHIFT;
  516. if ((master_state == I2C_STAT_MSTCODE_NACKADR) || (master_state == I2C_STAT_MSTCODE_NACKDAT))
  517. {
  518. /* Slave NACKed last byte, issue stop and return error */
  519. base->MSTCTL = I2C_MSTCTL_MSTSTOP_MASK;
  520. handle->state = kWaitForCompletionState;
  521. return kStatus_I2C_Nak;
  522. }
  523. err = kStatus_Success;
  524. switch (handle->state)
  525. {
  526. case kStartState:
  527. if (handle->remainingSubaddr)
  528. {
  529. /* Subaddress takes precedence over the data transfer, direction is always "write" in this case */
  530. base->MSTDAT = (uint32_t)transfer->slaveAddress << 1;
  531. handle->state = kTransmitSubaddrState;
  532. }
  533. else if (transfer->direction == kI2C_Write)
  534. {
  535. base->MSTDAT = (uint32_t)transfer->slaveAddress << 1;
  536. handle->state = handle->remainingBytes ? kTransmitDataState : kStopState;
  537. }
  538. else
  539. {
  540. base->MSTDAT = ((uint32_t)transfer->slaveAddress << 1) | 1u;
  541. handle->state = handle->remainingBytes ? kReceiveDataState : kStopState;
  542. }
  543. /* Send start condition */
  544. base->MSTCTL = I2C_MSTCTL_MSTSTART_MASK;
  545. break;
  546. case kTransmitSubaddrState:
  547. if (master_state != I2C_STAT_MSTCODE_TXREADY)
  548. {
  549. return kStatus_I2C_UnexpectedState;
  550. }
  551. /* Most significant subaddress byte comes first */
  552. base->MSTDAT = handle->subaddrBuf[handle->transfer.subaddressSize - handle->remainingSubaddr];
  553. base->MSTCTL = I2C_MSTCTL_MSTCONTINUE_MASK;
  554. if (--(handle->remainingSubaddr))
  555. {
  556. /* There are still subaddress bytes to be transmitted */
  557. break;
  558. }
  559. if (handle->remainingBytes)
  560. {
  561. /* There is data to be transferred, if there is write to read turnaround it is necessary to perform
  562. * repeated start */
  563. handle->state = (transfer->direction == kI2C_Read) ? kStartState : kTransmitDataState;
  564. }
  565. else
  566. {
  567. /* No more data, schedule stop condition */
  568. handle->state = kStopState;
  569. }
  570. break;
  571. case kTransmitDataState:
  572. if (master_state != I2C_STAT_MSTCODE_TXREADY)
  573. {
  574. return kStatus_I2C_UnexpectedState;
  575. }
  576. base->MSTDAT = *(handle->buf)++;
  577. base->MSTCTL = I2C_MSTCTL_MSTCONTINUE_MASK;
  578. if (--handle->remainingBytes == 0)
  579. {
  580. /* No more data, schedule stop condition */
  581. handle->state = kStopState;
  582. }
  583. handle->transferCount++;
  584. break;
  585. case kReceiveDataState:
  586. if (master_state != I2C_STAT_MSTCODE_RXREADY)
  587. {
  588. return kStatus_I2C_UnexpectedState;
  589. }
  590. *(handle->buf)++ = base->MSTDAT;
  591. if (--handle->remainingBytes)
  592. {
  593. base->MSTCTL = I2C_MSTCTL_MSTCONTINUE_MASK;
  594. }
  595. else
  596. {
  597. /* No more data expected, issue NACK and STOP right away */
  598. base->MSTCTL = I2C_MSTCTL_MSTSTOP_MASK;
  599. handle->state = kWaitForCompletionState;
  600. }
  601. handle->transferCount++;
  602. break;
  603. case kStopState:
  604. if (transfer->flags & kI2C_TransferNoStopFlag)
  605. {
  606. /* Stop condition is omitted, we are done */
  607. *isDone = true;
  608. handle->state = kIdleState;
  609. break;
  610. }
  611. /* Send stop condition */
  612. base->MSTCTL = I2C_MSTCTL_MSTSTOP_MASK;
  613. handle->state = kWaitForCompletionState;
  614. break;
  615. case kWaitForCompletionState:
  616. *isDone = true;
  617. handle->state = kIdleState;
  618. break;
  619. case kIdleState:
  620. default:
  621. /* State machine shall not be invoked again once it enters the idle state */
  622. err = kStatus_I2C_UnexpectedState;
  623. break;
  624. }
  625. return err;
  626. }
  627. void I2C_MasterTransferHandleIRQ(I2C_Type *base, i2c_master_handle_t *handle)
  628. {
  629. bool isDone;
  630. status_t result;
  631. /* Don't do anything if we don't have a valid handle. */
  632. if (!handle)
  633. {
  634. return;
  635. }
  636. result = I2C_RunTransferStateMachine(base, handle, &isDone);
  637. if (isDone || (result != kStatus_Success))
  638. {
  639. /* Disable internal IRQ enables. */
  640. I2C_DisableInterrupts(base, kI2C_MasterIrqFlags);
  641. /* Invoke callback. */
  642. if (handle->completionCallback)
  643. {
  644. handle->completionCallback(base, handle, result, handle->userData);
  645. }
  646. }
  647. }
  648. /*!
  649. * @brief Sets the hardware slave state machine to reset
  650. *
  651. * Per documentation, the only the state machine is reset, the configuration settings remain.
  652. *
  653. * @param base The I2C peripheral base address.
  654. */
  655. static void I2C_SlaveInternalStateMachineReset(I2C_Type *base)
  656. {
  657. I2C_SlaveEnable(base, false); /* clear SLVEN Slave enable bit */
  658. }
  659. /*!
  660. * @brief Compute CLKDIV
  661. *
  662. * This function computes CLKDIV value according to the given bus speed and Flexcomm source clock frequency.
  663. * This setting is used by hardware during slave clock stretching.
  664. *
  665. * @param base The I2C peripheral base address.
  666. * @return status of the operation
  667. */
  668. static status_t I2C_SlaveDivVal(uint32_t srcClock_Hz, i2c_slave_bus_speed_t busSpeed, uint32_t *divVal)
  669. {
  670. uint32_t dataSetupTime_ns;
  671. switch (busSpeed)
  672. {
  673. case kI2C_SlaveStandardMode:
  674. dataSetupTime_ns = 250u;
  675. break;
  676. case kI2C_SlaveFastMode:
  677. dataSetupTime_ns = 100u;
  678. break;
  679. case kI2C_SlaveFastModePlus:
  680. dataSetupTime_ns = 50u;
  681. break;
  682. case kI2C_SlaveHsMode:
  683. dataSetupTime_ns = 10u;
  684. break;
  685. default:
  686. dataSetupTime_ns = 0;
  687. break;
  688. }
  689. if (0 == dataSetupTime_ns)
  690. {
  691. return kStatus_InvalidArgument;
  692. }
  693. /* divVal = (sourceClock_Hz / 1000000) * (dataSetupTime_ns / 1000) */
  694. *divVal = srcClock_Hz / 1000u;
  695. *divVal = (*divVal) * dataSetupTime_ns;
  696. *divVal = (*divVal) / 1000000u;
  697. if ((*divVal) > I2C_CLKDIV_DIVVAL_MASK)
  698. {
  699. *divVal = I2C_CLKDIV_DIVVAL_MASK;
  700. }
  701. return kStatus_Success;
  702. }
  703. /*!
  704. * @brief Poll wait for the SLVPENDING flag.
  705. *
  706. * Wait for the pending status to be set (SLVPENDING = 1) by polling the STAT register.
  707. *
  708. * @param base The I2C peripheral base address.
  709. * @return status register at time the SLVPENDING bit is read as set
  710. */
  711. static uint32_t I2C_SlavePollPending(I2C_Type *base)
  712. {
  713. uint32_t stat;
  714. do
  715. {
  716. stat = base->STAT;
  717. } while (0u == (stat & I2C_STAT_SLVPENDING_MASK));
  718. return stat;
  719. }
  720. /*!
  721. * @brief Invoke event from I2C_SlaveTransferHandleIRQ().
  722. *
  723. * Sets the event type to transfer structure and invokes the event callback, if it has been
  724. * enabled by eventMask.
  725. *
  726. * @param base The I2C peripheral base address.
  727. * @param handle The I2C slave handle for non-blocking APIs.
  728. * @param event The I2C slave event to invoke.
  729. */
  730. static void I2C_SlaveInvokeEvent(I2C_Type *base, i2c_slave_handle_t *handle, i2c_slave_transfer_event_t event)
  731. {
  732. handle->transfer.event = event;
  733. if ((handle->callback) && (handle->transfer.eventMask & event))
  734. {
  735. handle->callback(base, &handle->transfer, handle->userData);
  736. /* if after event callback we have data buffer (callback func has added new data), keep transfer busy */
  737. if (false == handle->isBusy)
  738. {
  739. if (((handle->transfer.txData) && (handle->transfer.txSize)) ||
  740. ((handle->transfer.rxData) && (handle->transfer.rxSize)))
  741. {
  742. handle->isBusy = true;
  743. }
  744. }
  745. /* Clear the transferred count now that we have a new buffer. */
  746. if ((event == kI2C_SlaveReceiveEvent) || (event == kI2C_SlaveTransmitEvent))
  747. {
  748. handle->transfer.transferredCount = 0;
  749. }
  750. }
  751. }
  752. /*!
  753. * @brief Handle slave address match event.
  754. *
  755. * Called by Slave interrupt routine to ACK or NACK the matched address.
  756. * It also determines master direction (read or write).
  757. *
  758. * @param base The I2C peripheral base address.
  759. * @return true if the matched address is ACK'ed
  760. * @return false if the matched address is NACK'ed
  761. */
  762. static bool I2C_SlaveAddressIRQ(I2C_Type *base, i2c_slave_handle_t *handle)
  763. {
  764. uint8_t addressByte0;
  765. addressByte0 = (uint8_t)base->SLVDAT;
  766. /* store the matched address */
  767. handle->transfer.receivedAddress = addressByte0;
  768. /* R/nW */
  769. if (addressByte0 & 1u)
  770. {
  771. /* if we have no data in this transfer, call callback to get new */
  772. if ((handle->transfer.txData == NULL) || (handle->transfer.txSize == 0))
  773. {
  774. I2C_SlaveInvokeEvent(base, handle, kI2C_SlaveTransmitEvent);
  775. }
  776. /* NACK if we have no data in this transfer. */
  777. if ((handle->transfer.txData == NULL) || (handle->transfer.txSize == 0))
  778. {
  779. base->SLVCTL = I2C_SLVCTL_SLVNACK_MASK;
  780. return false;
  781. }
  782. /* master wants to read, so slave transmit is next state */
  783. handle->slaveFsm = kI2C_SlaveFsmTransmit;
  784. }
  785. else
  786. {
  787. /* if we have no receive buffer in this transfer, call callback to get new */
  788. if ((handle->transfer.rxData == NULL) || (handle->transfer.rxSize == 0))
  789. {
  790. I2C_SlaveInvokeEvent(base, handle, kI2C_SlaveReceiveEvent);
  791. }
  792. /* NACK if we have no data in this transfer */
  793. if ((handle->transfer.rxData == NULL) || (handle->transfer.rxSize == 0))
  794. {
  795. base->SLVCTL = I2C_SLVCTL_SLVNACK_MASK;
  796. return false;
  797. }
  798. /* master wants write, so slave receive is next state */
  799. handle->slaveFsm = kI2C_SlaveFsmReceive;
  800. }
  801. /* continue transaction */
  802. base->SLVCTL = I2C_SLVCTL_SLVCONTINUE_MASK;
  803. return true;
  804. }
  805. /*!
  806. * @brief Starts accepting slave transfers.
  807. *
  808. * Call this API after calling I2C_SlaveInit() and I2C_SlaveTransferCreateHandle() to start processing
  809. * transactions driven by an I2C master. The slave monitors the I2C bus and pass events to the
  810. * callback that was passed into the call to I2C_SlaveTransferCreateHandle(). The callback is always invoked
  811. * from the interrupt context.
  812. *
  813. * @param base The I2C peripheral base address.
  814. * @param handle Pointer to #i2c_slave_handle_t structure which stores the transfer state.
  815. * @param txData Data to be transmitted to master in response to master read from slave requests. NULL if slave RX only.
  816. * @param txSize Size of txData buffer in bytes.
  817. * @param rxData Data where received data from master will be stored in response to master write to slave requests. NULL
  818. * if slave TX only.
  819. * @param rxSize Size of rxData buffer in bytes.
  820. *
  821. * @retval #kStatus_Success Slave transfers were successfully started.
  822. * @retval #kStatus_I2C_Busy Slave transfers have already been started on this handle.
  823. */
  824. static status_t I2C_SlaveTransferNonBlockingInternal(I2C_Type *base,
  825. i2c_slave_handle_t *handle,
  826. const void *txData,
  827. size_t txSize,
  828. void *rxData,
  829. size_t rxSize,
  830. uint32_t eventMask)
  831. {
  832. status_t status;
  833. assert(handle);
  834. status = kStatus_Success;
  835. /* Disable I2C IRQ sources while we configure stuff. */
  836. I2C_DisableInterrupts(base, kI2C_SlaveIrqFlags);
  837. /* Return busy if another transaction is in progress. */
  838. if (handle->isBusy)
  839. {
  840. status = kStatus_I2C_Busy;
  841. }
  842. /* Save transfer into handle. */
  843. handle->transfer.txData = (const uint8_t *)(uintptr_t)txData;
  844. handle->transfer.txSize = txSize;
  845. handle->transfer.rxData = (uint8_t *)rxData;
  846. handle->transfer.rxSize = rxSize;
  847. handle->transfer.transferredCount = 0;
  848. handle->transfer.eventMask = eventMask | kI2C_SlaveTransmitEvent | kI2C_SlaveReceiveEvent;
  849. handle->isBusy = true;
  850. /* Set the SLVEN bit to 1 in the CFG register. */
  851. I2C_SlaveEnable(base, true);
  852. /* Clear w1c flags. */
  853. base->STAT |= 0u;
  854. /* Enable I2C internal IRQ sources. */
  855. I2C_EnableInterrupts(base, kI2C_SlaveIrqFlags);
  856. return status;
  857. }
  858. status_t I2C_SlaveSetSendBuffer(
  859. I2C_Type *base, volatile i2c_slave_transfer_t *transfer, const void *txData, size_t txSize, uint32_t eventMask)
  860. {
  861. return I2C_SlaveTransferNonBlockingInternal(base, transfer->handle, txData, txSize, NULL, 0u, eventMask);
  862. }
  863. status_t I2C_SlaveSetReceiveBuffer(
  864. I2C_Type *base, volatile i2c_slave_transfer_t *transfer, void *rxData, size_t rxSize, uint32_t eventMask)
  865. {
  866. return I2C_SlaveTransferNonBlockingInternal(base, transfer->handle, NULL, 0u, rxData, rxSize, eventMask);
  867. }
  868. void I2C_SlaveSetAddress(I2C_Type *base,
  869. i2c_slave_address_register_t addressRegister,
  870. uint8_t address,
  871. bool addressDisable)
  872. {
  873. base->SLVADR[addressRegister] = I2C_SLVADR_SLVADR(address) | I2C_SLVADR_SADISABLE(addressDisable);
  874. }
  875. void I2C_SlaveGetDefaultConfig(i2c_slave_config_t *slaveConfig)
  876. {
  877. assert(slaveConfig);
  878. i2c_slave_config_t mySlaveConfig = {0};
  879. /* default config enables slave address 0 match to general I2C call address zero */
  880. mySlaveConfig.enableSlave = true;
  881. mySlaveConfig.address1.addressDisable = true;
  882. mySlaveConfig.address2.addressDisable = true;
  883. mySlaveConfig.address3.addressDisable = true;
  884. *slaveConfig = mySlaveConfig;
  885. }
  886. status_t I2C_SlaveInit(I2C_Type *base, const i2c_slave_config_t *slaveConfig, uint32_t srcClock_Hz)
  887. {
  888. status_t status;
  889. uint32_t divVal = 0;
  890. /* configure data setup time used when slave stretches clock */
  891. status = I2C_SlaveDivVal(srcClock_Hz, slaveConfig->busSpeed, &divVal);
  892. if (kStatus_Success != status)
  893. {
  894. return status;
  895. }
  896. FLEXCOMM_Init(base, FLEXCOMM_PERIPH_I2C);
  897. /* I2C Clock Divider register */
  898. base->CLKDIV = divVal;
  899. /* set Slave address */
  900. I2C_SlaveSetAddress(base, kI2C_SlaveAddressRegister0, slaveConfig->address0.address,
  901. slaveConfig->address0.addressDisable);
  902. I2C_SlaveSetAddress(base, kI2C_SlaveAddressRegister1, slaveConfig->address1.address,
  903. slaveConfig->address1.addressDisable);
  904. I2C_SlaveSetAddress(base, kI2C_SlaveAddressRegister2, slaveConfig->address2.address,
  905. slaveConfig->address2.addressDisable);
  906. I2C_SlaveSetAddress(base, kI2C_SlaveAddressRegister3, slaveConfig->address3.address,
  907. slaveConfig->address3.addressDisable);
  908. /* set Slave address 0 qual */
  909. base->SLVQUAL0 = I2C_SLVQUAL0_QUALMODE0(slaveConfig->qualMode) | I2C_SLVQUAL0_SLVQUAL0(slaveConfig->qualAddress);
  910. /* set Slave enable */
  911. base->CFG = I2C_CFG_SLVEN(slaveConfig->enableSlave);
  912. return status;
  913. }
  914. void I2C_SlaveDeinit(I2C_Type *base)
  915. {
  916. I2C_SlaveEnable(base, false);
  917. }
  918. status_t I2C_SlaveWriteBlocking(I2C_Type *base, const uint8_t *txBuff, size_t txSize)
  919. {
  920. const uint8_t *buf = txBuff;
  921. uint32_t stat;
  922. bool slaveAddress;
  923. bool slaveTransmit;
  924. /* Set the SLVEN bit to 1 in the CFG register. */
  925. I2C_SlaveEnable(base, true);
  926. /* wait for SLVPENDING */
  927. stat = I2C_SlavePollPending(base);
  928. /* Get slave machine state */
  929. slaveAddress = (((stat & I2C_STAT_SLVSTATE_MASK) >> I2C_STAT_SLVSTATE_SHIFT) == I2C_STAT_SLVST_ADDR);
  930. slaveTransmit = (((stat & I2C_STAT_SLVSTATE_MASK) >> I2C_STAT_SLVSTATE_SHIFT) == I2C_STAT_SLVST_TX);
  931. /* in I2C_SlaveSend() it shall be either slaveAddress or slaveTransmit */
  932. if (!(slaveAddress || slaveTransmit))
  933. {
  934. I2C_SlaveInternalStateMachineReset(base);
  935. return kStatus_Fail;
  936. }
  937. if (slaveAddress)
  938. {
  939. /* Acknowledge (ack) the address by setting SLVCONTINUE = 1 in the slave control register */
  940. base->SLVCTL = I2C_SLVCTL_SLVCONTINUE_MASK;
  941. /* wait for SLVPENDING */
  942. stat = I2C_SlavePollPending(base);
  943. }
  944. /* send bytes up to txSize */
  945. while (txSize)
  946. {
  947. slaveTransmit = (((stat & I2C_STAT_SLVSTATE_MASK) >> I2C_STAT_SLVSTATE_SHIFT) == I2C_STAT_SLVST_TX);
  948. if (!slaveTransmit)
  949. {
  950. I2C_SlaveInternalStateMachineReset(base);
  951. return kStatus_Fail;
  952. }
  953. /* Write 8 bits of data to the SLVDAT register */
  954. base->SLVDAT = I2C_SLVDAT_DATA(*buf);
  955. /* continue transaction */
  956. base->SLVCTL = I2C_SLVCTL_SLVCONTINUE_MASK;
  957. /* advance counters and pointers for next data */
  958. buf++;
  959. txSize--;
  960. if (txSize)
  961. {
  962. /* wait for SLVPENDING */
  963. stat = I2C_SlavePollPending(base);
  964. }
  965. }
  966. return kStatus_Success;
  967. }
  968. status_t I2C_SlaveReadBlocking(I2C_Type *base, uint8_t *rxBuff, size_t rxSize)
  969. {
  970. uint8_t *buf = rxBuff;
  971. uint32_t stat;
  972. bool slaveAddress;
  973. bool slaveReceive;
  974. /* Set the SLVEN bit to 1 in the CFG register. */
  975. I2C_SlaveEnable(base, true);
  976. /* wait for SLVPENDING */
  977. stat = I2C_SlavePollPending(base);
  978. /* Get slave machine state */
  979. slaveAddress = (((stat & I2C_STAT_SLVSTATE_MASK) >> I2C_STAT_SLVSTATE_SHIFT) == I2C_STAT_SLVST_ADDR);
  980. slaveReceive = (((stat & I2C_STAT_SLVSTATE_MASK) >> I2C_STAT_SLVSTATE_SHIFT) == I2C_STAT_SLVST_RX);
  981. /* in I2C_SlaveReceive() it shall be either slaveAddress or slaveReceive */
  982. if (!(slaveAddress || slaveReceive))
  983. {
  984. I2C_SlaveInternalStateMachineReset(base);
  985. return kStatus_Fail;
  986. }
  987. if (slaveAddress)
  988. {
  989. /* Acknowledge (ack) the address by setting SLVCONTINUE = 1 in the slave control register */
  990. base->SLVCTL = I2C_SLVCTL_SLVCONTINUE_MASK;
  991. /* wait for SLVPENDING */
  992. stat = I2C_SlavePollPending(base);
  993. }
  994. /* receive bytes up to rxSize */
  995. while (rxSize)
  996. {
  997. slaveReceive = (((stat & I2C_STAT_SLVSTATE_MASK) >> I2C_STAT_SLVSTATE_SHIFT) == I2C_STAT_SLVST_RX);
  998. if (!slaveReceive)
  999. {
  1000. I2C_SlaveInternalStateMachineReset(base);
  1001. return kStatus_Fail;
  1002. }
  1003. /* Read 8 bits of data from the SLVDAT register */
  1004. *buf = (uint8_t)base->SLVDAT;
  1005. /* continue transaction */
  1006. base->SLVCTL = I2C_SLVCTL_SLVCONTINUE_MASK;
  1007. /* advance counters and pointers for next data */
  1008. buf++;
  1009. rxSize--;
  1010. if (rxSize)
  1011. {
  1012. /* wait for SLVPENDING */
  1013. stat = I2C_SlavePollPending(base);
  1014. }
  1015. }
  1016. return kStatus_Success;
  1017. }
  1018. void I2C_SlaveTransferCreateHandle(I2C_Type *base,
  1019. i2c_slave_handle_t *handle,
  1020. i2c_slave_transfer_callback_t callback,
  1021. void *userData)
  1022. {
  1023. uint32_t instance;
  1024. assert(handle);
  1025. /* Clear out the handle. */
  1026. memset(handle, 0, sizeof(*handle));
  1027. /* Look up instance number */
  1028. instance = I2C_GetInstance(base);
  1029. /* Save base and instance. */
  1030. handle->callback = callback;
  1031. handle->userData = userData;
  1032. /* initialize fsm */
  1033. handle->slaveFsm = kI2C_SlaveFsmAddressMatch;
  1034. /* store pointer to handle into transfer struct */
  1035. handle->transfer.handle = handle;
  1036. FLEXCOMM_SetIRQHandler(base, (flexcomm_irq_handler_t)(uintptr_t)I2C_SlaveTransferHandleIRQ, handle);
  1037. /* Clear internal IRQ enables and enable NVIC IRQ. */
  1038. I2C_DisableInterrupts(base, kI2C_SlaveIrqFlags);
  1039. EnableIRQ(s_i2cIRQ[instance]);
  1040. }
  1041. status_t I2C_SlaveTransferNonBlocking(I2C_Type *base, i2c_slave_handle_t *handle, uint32_t eventMask)
  1042. {
  1043. return I2C_SlaveTransferNonBlockingInternal(base, handle, NULL, 0u, NULL, 0u, eventMask);
  1044. }
  1045. status_t I2C_SlaveTransferGetCount(I2C_Type *base, i2c_slave_handle_t *handle, size_t *count)
  1046. {
  1047. assert(handle);
  1048. if (!count)
  1049. {
  1050. return kStatus_InvalidArgument;
  1051. }
  1052. /* Catch when there is not an active transfer. */
  1053. if (!handle->isBusy)
  1054. {
  1055. *count = 0;
  1056. return kStatus_NoTransferInProgress;
  1057. }
  1058. /* For an active transfer, just return the count from the handle. */
  1059. *count = handle->transfer.transferredCount;
  1060. return kStatus_Success;
  1061. }
  1062. void I2C_SlaveTransferAbort(I2C_Type *base, i2c_slave_handle_t *handle)
  1063. {
  1064. /* Disable I2C IRQ sources while we configure stuff. */
  1065. I2C_DisableInterrupts(base, kI2C_SlaveIrqFlags);
  1066. /* Set the SLVEN bit to 0 in the CFG register. */
  1067. I2C_SlaveEnable(base, false);
  1068. handle->isBusy = false;
  1069. handle->transfer.txSize = 0;
  1070. handle->transfer.rxSize = 0;
  1071. }
  1072. void I2C_SlaveTransferHandleIRQ(I2C_Type *base, i2c_slave_handle_t *handle)
  1073. {
  1074. uint32_t i2cStatus = base->STAT;
  1075. if (i2cStatus & I2C_STAT_SLVDESEL_MASK)
  1076. {
  1077. I2C_SlaveInvokeEvent(base, handle, kI2C_SlaveDeselectedEvent);
  1078. I2C_SlaveClearStatusFlags(base, I2C_STAT_SLVDESEL_MASK);
  1079. }
  1080. /* SLVPENDING flag is cleared by writing I2C_SLVCTL_SLVCONTINUE_MASK to SLVCTL register */
  1081. if (i2cStatus & I2C_STAT_SLVPENDING_MASK)
  1082. {
  1083. bool slaveAddress = (((i2cStatus & I2C_STAT_SLVSTATE_MASK) >> I2C_STAT_SLVSTATE_SHIFT) == I2C_STAT_SLVST_ADDR);
  1084. if (slaveAddress)
  1085. {
  1086. I2C_SlaveAddressIRQ(base, handle);
  1087. I2C_SlaveInvokeEvent(base, handle, kI2C_SlaveAddressMatchEvent);
  1088. }
  1089. else
  1090. {
  1091. switch (handle->slaveFsm)
  1092. {
  1093. case kI2C_SlaveFsmReceive:
  1094. {
  1095. bool slaveReceive =
  1096. (((i2cStatus & I2C_STAT_SLVSTATE_MASK) >> I2C_STAT_SLVSTATE_SHIFT) == I2C_STAT_SLVST_RX);
  1097. if (slaveReceive)
  1098. {
  1099. /* if we have no receive buffer in this transfer, call callback to get new */
  1100. if ((handle->transfer.rxData == NULL) || (handle->transfer.rxSize == 0))
  1101. {
  1102. I2C_SlaveInvokeEvent(base, handle, kI2C_SlaveReceiveEvent);
  1103. }
  1104. /* receive a byte */
  1105. if ((handle->transfer.rxData) && (handle->transfer.rxSize))
  1106. {
  1107. *(handle->transfer.rxData) = (uint8_t)base->SLVDAT;
  1108. (handle->transfer.rxSize)--;
  1109. (handle->transfer.rxData)++;
  1110. (handle->transfer.transferredCount)++;
  1111. /* continue transaction */
  1112. base->SLVCTL = I2C_SLVCTL_SLVCONTINUE_MASK;
  1113. }
  1114. /* is this last transaction for this transfer? allow next transaction */
  1115. if ((0 == handle->transfer.rxSize) && (0 == handle->transfer.txSize))
  1116. {
  1117. handle->isBusy = false;
  1118. I2C_SlaveInvokeEvent(base, handle, kI2C_SlaveCompletionEvent);
  1119. }
  1120. }
  1121. else
  1122. {
  1123. base->SLVCTL = I2C_SLVCTL_SLVNACK_MASK;
  1124. }
  1125. }
  1126. break;
  1127. case kI2C_SlaveFsmTransmit:
  1128. {
  1129. bool slaveTransmit =
  1130. (((i2cStatus & I2C_STAT_SLVSTATE_MASK) >> I2C_STAT_SLVSTATE_SHIFT) == I2C_STAT_SLVST_TX);
  1131. if (slaveTransmit)
  1132. {
  1133. /* if we have no data in this transfer, call callback to get new */
  1134. if ((handle->transfer.txData == NULL) || (handle->transfer.txSize == 0))
  1135. {
  1136. I2C_SlaveInvokeEvent(base, handle, kI2C_SlaveTransmitEvent);
  1137. }
  1138. /* transmit a byte */
  1139. if ((handle->transfer.txData) && (handle->transfer.txSize))
  1140. {
  1141. base->SLVDAT = *(handle->transfer.txData);
  1142. (handle->transfer.txSize)--;
  1143. (handle->transfer.txData)++;
  1144. (handle->transfer.transferredCount)++;
  1145. /* continue transaction */
  1146. base->SLVCTL = I2C_SLVCTL_SLVCONTINUE_MASK;
  1147. }
  1148. /* is this last transaction for this transfer? allow next transaction */
  1149. if ((0 == handle->transfer.rxSize) && (0 == handle->transfer.txSize))
  1150. {
  1151. handle->isBusy = false;
  1152. I2C_SlaveInvokeEvent(base, handle, kI2C_SlaveCompletionEvent);
  1153. }
  1154. }
  1155. else
  1156. {
  1157. base->SLVCTL = I2C_SLVCTL_SLVNACK_MASK;
  1158. }
  1159. }
  1160. break;
  1161. default:
  1162. /* incorrect state, slv_abort()? */
  1163. break;
  1164. }
  1165. }
  1166. }
  1167. }