fsl_i2c.c 46 KB

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