fsl_lpi2c.c 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478
  1. /*
  2. * Copyright (c) 2015, Freescale Semiconductor, Inc.
  3. * Copyright 2016-2021 NXP
  4. * All rights reserved.
  5. *
  6. * SPDX-License-Identifier: BSD-3-Clause
  7. */
  8. #include "fsl_lpi2c.h"
  9. #include <stdlib.h>
  10. #include <string.h>
  11. /*******************************************************************************
  12. * Definitions
  13. ******************************************************************************/
  14. /* Component ID definition, used by tools. */
  15. #ifndef FSL_COMPONENT_ID
  16. #define FSL_COMPONENT_ID "platform.drivers.lpi2c"
  17. #endif
  18. /* ! @brief LPI2C master fifo commands. */
  19. enum
  20. {
  21. kTxDataCmd = LPI2C_MTDR_CMD(0x0U), /*!< Transmit DATA[7:0] */
  22. kRxDataCmd = LPI2C_MTDR_CMD(0X1U), /*!< Receive (DATA[7:0] + 1) bytes */
  23. kStopCmd = LPI2C_MTDR_CMD(0x2U), /*!< Generate STOP condition */
  24. kStartCmd = LPI2C_MTDR_CMD(0x4U), /*!< Generate(repeated) START and transmit address in DATA[[7:0] */
  25. };
  26. /*!
  27. * @brief Default watermark values.
  28. *
  29. * The default watermarks are set to zero.
  30. */
  31. enum
  32. {
  33. kDefaultTxWatermark = 0,
  34. kDefaultRxWatermark = 0,
  35. };
  36. /*! @brief States for the state machine used by transactional APIs. */
  37. enum
  38. {
  39. kIdleState = 0,
  40. kSendCommandState,
  41. kIssueReadCommandState,
  42. kTransferDataState,
  43. kStopState,
  44. kWaitForCompletionState,
  45. };
  46. /*! @brief Typedef for slave interrupt handler. */
  47. typedef void (*lpi2c_slave_isr_t)(LPI2C_Type *base, lpi2c_slave_handle_t *handle);
  48. /*******************************************************************************
  49. * Prototypes
  50. ******************************************************************************/
  51. static uint32_t LPI2C_GetCyclesForWidth(
  52. uint32_t sourceClock_Hz, uint32_t width_ns, uint32_t minCycles, uint32_t maxCycles, uint32_t prescaler);
  53. static status_t LPI2C_MasterWaitForTxReady(LPI2C_Type *base);
  54. static status_t LPI2C_RunTransferStateMachine(LPI2C_Type *base, lpi2c_master_handle_t *handle, bool *isDone);
  55. static void LPI2C_InitTransferStateMachine(lpi2c_master_handle_t *handle);
  56. static status_t LPI2C_SlaveCheckAndClearError(LPI2C_Type *base, uint32_t flags);
  57. static void LPI2C_CommonIRQHandler(LPI2C_Type *base, uint32_t instance);
  58. /*******************************************************************************
  59. * Variables
  60. ******************************************************************************/
  61. /*! @brief Array to map LPI2C instance number to base pointer. */
  62. static LPI2C_Type *const kLpi2cBases[] = LPI2C_BASE_PTRS;
  63. /*! @brief Array to map LPI2C instance number to IRQ number, used internally for LPI2C master interrupt and EDMA
  64. transactional APIs. */
  65. IRQn_Type const kLpi2cIrqs[] = LPI2C_IRQS;
  66. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  67. /*! @brief Array to map LPI2C instance number to clock gate enum. */
  68. static clock_ip_name_t const kLpi2cClocks[] = LPI2C_CLOCKS;
  69. #if defined(LPI2C_PERIPH_CLOCKS)
  70. /*! @brief Array to map LPI2C instance number to pheripheral clock gate enum. */
  71. static const clock_ip_name_t kLpi2cPeriphClocks[] = LPI2C_PERIPH_CLOCKS;
  72. #endif
  73. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  74. /*! @brief Pointer to master IRQ handler for each instance, used internally for LPI2C master interrupt and EDMA
  75. transactional APIs. */
  76. lpi2c_master_isr_t s_lpi2cMasterIsr;
  77. /*! @brief Pointers to master handles for each instance, used internally for LPI2C master interrupt and EDMA
  78. transactional APIs. */
  79. void *s_lpi2cMasterHandle[ARRAY_SIZE(kLpi2cBases)];
  80. /*! @brief Pointer to slave IRQ handler for each instance. */
  81. static lpi2c_slave_isr_t s_lpi2cSlaveIsr;
  82. /*! @brief Pointers to slave handles for each instance. */
  83. static lpi2c_slave_handle_t *s_lpi2cSlaveHandle[ARRAY_SIZE(kLpi2cBases)];
  84. /*******************************************************************************
  85. * Code
  86. ******************************************************************************/
  87. /*!
  88. * brief Returns an instance number given a base address.
  89. *
  90. * If an invalid base address is passed, debug builds will assert. Release builds will just return
  91. * instance number 0.
  92. *
  93. * param base The LPI2C peripheral base address.
  94. * return LPI2C instance number starting from 0.
  95. */
  96. uint32_t LPI2C_GetInstance(LPI2C_Type *base)
  97. {
  98. uint32_t instance;
  99. for (instance = 0U; instance < ARRAY_SIZE(kLpi2cBases); ++instance)
  100. {
  101. if (kLpi2cBases[instance] == base)
  102. {
  103. break;
  104. }
  105. }
  106. assert(instance < ARRAY_SIZE(kLpi2cBases));
  107. return instance;
  108. }
  109. /*!
  110. * @brief Computes a cycle count for a given time in nanoseconds.
  111. * @param sourceClock_Hz LPI2C functional clock frequency in Hertz.
  112. * @param width_ns Desired with in nanoseconds.
  113. * @param minCycles Minimum cycle count.
  114. * @param maxCycles Maximum cycle count.
  115. * @param prescaler LPI2C prescaler setting. If the cycle period is not affected by the prescaler value, set it to 0.
  116. */
  117. static uint32_t LPI2C_GetCyclesForWidth(
  118. uint32_t sourceClock_Hz, uint32_t width_ns, uint32_t minCycles, uint32_t maxCycles, uint32_t prescaler)
  119. {
  120. assert(sourceClock_Hz > 0U);
  121. uint32_t divider = 1U;
  122. while (prescaler != 0U)
  123. {
  124. divider *= 2U;
  125. prescaler--;
  126. }
  127. uint32_t busCycle_ns = 1000000U / (sourceClock_Hz / divider / 1000U);
  128. /* Calculate the cycle count, round up the calculated value. */
  129. uint32_t cycles = (width_ns * 10U / busCycle_ns + 5U) / 10U;
  130. /* If the calculated value is smaller than the minimum value, use the minimum value */
  131. if (cycles < minCycles)
  132. {
  133. cycles = minCycles;
  134. }
  135. /* If the calculated value is larger than the maximum value, use the maxmum value */
  136. if (cycles > maxCycles)
  137. {
  138. cycles = maxCycles;
  139. }
  140. return cycles;
  141. }
  142. /*!
  143. * @brief Convert provided flags to status code, and clear any errors if present.
  144. * @param base The LPI2C peripheral base address.
  145. * @param status Current status flags value that will be checked.
  146. * @retval #kStatus_Success
  147. * @retval #kStatus_LPI2C_PinLowTimeout
  148. * @retval #kStatus_LPI2C_ArbitrationLost
  149. * @retval #kStatus_LPI2C_Nak
  150. * @retval #kStatus_LPI2C_FifoError
  151. */
  152. /* Not static so it can be used from fsl_lpi2c_edma.c. */
  153. status_t LPI2C_MasterCheckAndClearError(LPI2C_Type *base, uint32_t status)
  154. {
  155. status_t result = kStatus_Success;
  156. /* Check for error. These errors cause a stop to automatically be sent. We must */
  157. /* clear the errors before a new transfer can start. */
  158. status &= (uint32_t)kLPI2C_MasterErrorFlags;
  159. if (0U != status)
  160. {
  161. /* Select the correct error code. Ordered by severity, with bus issues first. */
  162. if (0U != (status & (uint32_t)kLPI2C_MasterPinLowTimeoutFlag))
  163. {
  164. result = kStatus_LPI2C_PinLowTimeout;
  165. }
  166. else if (0U != (status & (uint32_t)kLPI2C_MasterArbitrationLostFlag))
  167. {
  168. result = kStatus_LPI2C_ArbitrationLost;
  169. }
  170. else if (0U != (status & (uint32_t)kLPI2C_MasterNackDetectFlag))
  171. {
  172. result = kStatus_LPI2C_Nak;
  173. }
  174. else if (0U != (status & (uint32_t)kLPI2C_MasterFifoErrFlag))
  175. {
  176. result = kStatus_LPI2C_FifoError;
  177. }
  178. else
  179. {
  180. ; /* Intentional empty */
  181. }
  182. /* Clear the flags. */
  183. LPI2C_MasterClearStatusFlags(base, status);
  184. /* Reset fifos. These flags clear automatically. */
  185. base->MCR |= LPI2C_MCR_RRF_MASK | LPI2C_MCR_RTF_MASK;
  186. }
  187. else
  188. {
  189. ; /* Intentional empty */
  190. }
  191. return result;
  192. }
  193. /*!
  194. * @brief Wait until there is room in the tx fifo.
  195. * @param base The LPI2C peripheral base address.
  196. * @retval #kStatus_Success
  197. * @retval #kStatus_LPI2C_PinLowTimeout
  198. * @retval #kStatus_LPI2C_ArbitrationLost
  199. * @retval #kStatus_LPI2C_Nak
  200. * @retval #kStatus_LPI2C_FifoError
  201. */
  202. static status_t LPI2C_MasterWaitForTxReady(LPI2C_Type *base)
  203. {
  204. status_t result = kStatus_Success;
  205. uint32_t status;
  206. size_t txCount;
  207. size_t txFifoSize = (size_t)FSL_FEATURE_LPI2C_FIFO_SIZEn(base);
  208. #if I2C_RETRY_TIMES != 0U
  209. uint32_t waitTimes = I2C_RETRY_TIMES;
  210. #endif
  211. do
  212. {
  213. /* Get the number of words in the tx fifo and compute empty slots. */
  214. LPI2C_MasterGetFifoCounts(base, NULL, &txCount);
  215. txCount = txFifoSize - txCount;
  216. /* Check for error flags. */
  217. status = LPI2C_MasterGetStatusFlags(base);
  218. result = LPI2C_MasterCheckAndClearError(base, status);
  219. if (kStatus_Success != result)
  220. {
  221. break;
  222. }
  223. #if I2C_RETRY_TIMES != 0U
  224. waitTimes--;
  225. } while ((0U == txCount) && (0U != waitTimes));
  226. if (0U == waitTimes)
  227. {
  228. result = kStatus_LPI2C_Timeout;
  229. }
  230. #else
  231. } while (0U == txCount);
  232. #endif
  233. return result;
  234. }
  235. /*!
  236. * @brief Make sure the bus isn't already busy.
  237. *
  238. * A busy bus is allowed if we are the one driving it.
  239. *
  240. * @param base The LPI2C peripheral base address.
  241. * @retval #kStatus_Success
  242. * @retval #kStatus_LPI2C_Busy
  243. */
  244. /* Not static so it can be used from fsl_lpi2c_edma.c. */
  245. status_t LPI2C_CheckForBusyBus(LPI2C_Type *base)
  246. {
  247. status_t ret = kStatus_Success;
  248. uint32_t status = LPI2C_MasterGetStatusFlags(base);
  249. if ((0U != (status & (uint32_t)kLPI2C_MasterBusBusyFlag)) && (0U == (status & (uint32_t)kLPI2C_MasterBusyFlag)))
  250. {
  251. ret = kStatus_LPI2C_Busy;
  252. }
  253. return ret;
  254. }
  255. /*!
  256. * brief Provides a default configuration for the LPI2C master peripheral.
  257. *
  258. * This function provides the following default configuration for the LPI2C master peripheral:
  259. * code
  260. * masterConfig->enableMaster = true;
  261. * masterConfig->debugEnable = false;
  262. * masterConfig->ignoreAck = false;
  263. * masterConfig->pinConfig = kLPI2C_2PinOpenDrain;
  264. * masterConfig->baudRate_Hz = 100000U;
  265. * masterConfig->busIdleTimeout_ns = 0U;
  266. * masterConfig->pinLowTimeout_ns = 0U;
  267. * masterConfig->sdaGlitchFilterWidth_ns = 0U;
  268. * masterConfig->sclGlitchFilterWidth_ns = 0U;
  269. * masterConfig->hostRequest.enable = false;
  270. * masterConfig->hostRequest.source = kLPI2C_HostRequestExternalPin;
  271. * masterConfig->hostRequest.polarity = kLPI2C_HostRequestPinActiveHigh;
  272. * endcode
  273. *
  274. * After calling this function, you can override any settings in order to customize the configuration,
  275. * prior to initializing the master driver with LPI2C_MasterInit().
  276. *
  277. * param[out] masterConfig User provided configuration structure for default values. Refer to #lpi2c_master_config_t.
  278. */
  279. void LPI2C_MasterGetDefaultConfig(lpi2c_master_config_t *masterConfig)
  280. {
  281. /* Initializes the configure structure to zero. */
  282. (void)memset(masterConfig, 0, sizeof(*masterConfig));
  283. masterConfig->enableMaster = true;
  284. masterConfig->debugEnable = false;
  285. masterConfig->enableDoze = true;
  286. masterConfig->ignoreAck = false;
  287. masterConfig->pinConfig = kLPI2C_2PinOpenDrain;
  288. masterConfig->baudRate_Hz = 100000U;
  289. masterConfig->busIdleTimeout_ns = 0U; /* Set to 0 to disable the function */
  290. masterConfig->pinLowTimeout_ns = 0U; /* Set to 0 to disable the function */
  291. masterConfig->sdaGlitchFilterWidth_ns = 0U; /* Set to 0 to disable the function */
  292. masterConfig->sclGlitchFilterWidth_ns = 0U; /* Set to 0 to disable the function */
  293. masterConfig->hostRequest.enable = false;
  294. masterConfig->hostRequest.source = kLPI2C_HostRequestExternalPin;
  295. masterConfig->hostRequest.polarity = kLPI2C_HostRequestPinActiveHigh;
  296. }
  297. /*!
  298. * brief Initializes the LPI2C master peripheral.
  299. *
  300. * This function enables the peripheral clock and initializes the LPI2C master peripheral as described by the user
  301. * provided configuration. A software reset is performed prior to configuration.
  302. *
  303. * param base The LPI2C peripheral base address.
  304. * param masterConfig User provided peripheral configuration. Use LPI2C_MasterGetDefaultConfig() to get a set of
  305. * defaults
  306. * that you can override.
  307. * param sourceClock_Hz Frequency in Hertz of the LPI2C functional clock. Used to calculate the baud rate divisors,
  308. * filter widths, and timeout periods.
  309. */
  310. void LPI2C_MasterInit(LPI2C_Type *base, const lpi2c_master_config_t *masterConfig, uint32_t sourceClock_Hz)
  311. {
  312. uint32_t prescaler;
  313. uint32_t cycles;
  314. uint32_t cfgr2;
  315. uint32_t value;
  316. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  317. uint32_t instance = LPI2C_GetInstance(base);
  318. /* Ungate the clock. */
  319. (void)CLOCK_EnableClock(kLpi2cClocks[instance]);
  320. #if defined(LPI2C_PERIPH_CLOCKS)
  321. /* Ungate the functional clock in initialize function. */
  322. CLOCK_EnableClock(kLpi2cPeriphClocks[instance]);
  323. #endif
  324. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  325. /* Reset peripheral before configuring it. */
  326. LPI2C_MasterReset(base);
  327. /* Doze bit: 0 is enable, 1 is disable */
  328. base->MCR = LPI2C_MCR_DBGEN(masterConfig->debugEnable) | LPI2C_MCR_DOZEN(!(masterConfig->enableDoze));
  329. /* host request */
  330. value = base->MCFGR0;
  331. value &= (~(LPI2C_MCFGR0_HREN_MASK | LPI2C_MCFGR0_HRPOL_MASK | LPI2C_MCFGR0_HRSEL_MASK));
  332. value |= LPI2C_MCFGR0_HREN(masterConfig->hostRequest.enable) |
  333. LPI2C_MCFGR0_HRPOL(masterConfig->hostRequest.polarity) |
  334. LPI2C_MCFGR0_HRSEL(masterConfig->hostRequest.source);
  335. base->MCFGR0 = value;
  336. /* pin config and ignore ack */
  337. value = base->MCFGR1;
  338. value &= ~(LPI2C_MCFGR1_PINCFG_MASK | LPI2C_MCFGR1_IGNACK_MASK);
  339. value |= LPI2C_MCFGR1_PINCFG(masterConfig->pinConfig);
  340. value |= LPI2C_MCFGR1_IGNACK(masterConfig->ignoreAck);
  341. base->MCFGR1 = value;
  342. LPI2C_MasterSetWatermarks(base, (size_t)kDefaultTxWatermark, (size_t)kDefaultRxWatermark);
  343. /* Configure glitch filters. */
  344. cfgr2 = base->MCFGR2;
  345. if (0U != (masterConfig->sdaGlitchFilterWidth_ns))
  346. {
  347. /* Calculate SDA filter width. The width is equal to FILTSDA cycles of functional clock.
  348. And set FILTSDA to 0 disables the fileter, so the min value is 1. */
  349. cycles = LPI2C_GetCyclesForWidth(sourceClock_Hz, masterConfig->sdaGlitchFilterWidth_ns, 1U,
  350. (LPI2C_MCFGR2_FILTSDA_MASK >> LPI2C_MCFGR2_FILTSDA_SHIFT), 0U);
  351. cfgr2 &= ~LPI2C_MCFGR2_FILTSDA_MASK;
  352. cfgr2 |= LPI2C_MCFGR2_FILTSDA(cycles);
  353. }
  354. if (0U != masterConfig->sclGlitchFilterWidth_ns)
  355. {
  356. /* Calculate SDL filter width. The width is equal to FILTSCL cycles of functional clock.
  357. And set FILTSCL to 0 disables the fileter, so the min value is 1. */
  358. cycles = LPI2C_GetCyclesForWidth(sourceClock_Hz, masterConfig->sclGlitchFilterWidth_ns, 1U,
  359. (LPI2C_MCFGR2_FILTSCL_MASK >> LPI2C_MCFGR2_FILTSCL_SHIFT), 0U);
  360. cfgr2 &= ~LPI2C_MCFGR2_FILTSCL_MASK;
  361. cfgr2 |= LPI2C_MCFGR2_FILTSCL(cycles);
  362. }
  363. base->MCFGR2 = cfgr2;
  364. /* Configure baudrate after the SDA/SCL glitch filter setting,
  365. since the baudrate calculation needs them as parameter. */
  366. LPI2C_MasterSetBaudRate(base, sourceClock_Hz, masterConfig->baudRate_Hz);
  367. /* Configure bus idle and pin low timeouts after baudrate setting,
  368. since the timeout calculation needs prescaler as parameter. */
  369. prescaler = (base->MCFGR1 & LPI2C_MCFGR1_PRESCALE_MASK) >> LPI2C_MCFGR1_PRESCALE_SHIFT;
  370. if (0U != (masterConfig->busIdleTimeout_ns))
  371. {
  372. /* Calculate bus idle timeout value. The value is equal to BUSIDLE cycles of functional clock divided by
  373. prescaler. And set BUSIDLE to 0 disables the fileter, so the min value is 1. */
  374. cycles = LPI2C_GetCyclesForWidth(sourceClock_Hz, masterConfig->busIdleTimeout_ns, 1U,
  375. (LPI2C_MCFGR2_BUSIDLE_MASK >> LPI2C_MCFGR2_BUSIDLE_SHIFT), prescaler);
  376. cfgr2 &= ~LPI2C_MCFGR2_BUSIDLE_MASK;
  377. cfgr2 |= LPI2C_MCFGR2_BUSIDLE(cycles);
  378. }
  379. base->MCFGR2 = cfgr2;
  380. if (0U != masterConfig->pinLowTimeout_ns)
  381. {
  382. /* Calculate bus pin low timeout value. The value is equal to PINLOW cycles of functional clock divided by
  383. prescaler. And set PINLOW to 0 disables the fileter, so the min value is 1. */
  384. cycles = LPI2C_GetCyclesForWidth(sourceClock_Hz, masterConfig->pinLowTimeout_ns / 256U, 1U,
  385. (LPI2C_MCFGR2_BUSIDLE_MASK >> LPI2C_MCFGR2_BUSIDLE_SHIFT), prescaler);
  386. base->MCFGR3 = (base->MCFGR3 & ~LPI2C_MCFGR3_PINLOW_MASK) | LPI2C_MCFGR3_PINLOW(cycles);
  387. }
  388. LPI2C_MasterEnable(base, masterConfig->enableMaster);
  389. }
  390. /*!
  391. * brief Deinitializes the LPI2C master peripheral.
  392. *
  393. * This function disables the LPI2C master peripheral and gates the clock. It also performs a software
  394. * reset to restore the peripheral to reset conditions.
  395. *
  396. * param base The LPI2C peripheral base address.
  397. */
  398. void LPI2C_MasterDeinit(LPI2C_Type *base)
  399. {
  400. /* Restore to reset state. */
  401. LPI2C_MasterReset(base);
  402. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  403. uint32_t instance = LPI2C_GetInstance(base);
  404. /* Gate clock. */
  405. (void)CLOCK_DisableClock(kLpi2cClocks[instance]);
  406. #if defined(LPI2C_PERIPH_CLOCKS)
  407. /* Gate the functional clock. */
  408. CLOCK_DisableClock(kLpi2cPeriphClocks[instance]);
  409. #endif
  410. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  411. }
  412. /*!
  413. * brief Configures LPI2C master data match feature.
  414. *
  415. * param base The LPI2C peripheral base address.
  416. * param matchConfig Settings for the data match feature.
  417. */
  418. void LPI2C_MasterConfigureDataMatch(LPI2C_Type *base, const lpi2c_data_match_config_t *matchConfig)
  419. {
  420. /* Disable master mode. */
  421. bool wasEnabled = (0U != ((base->MCR & LPI2C_MCR_MEN_MASK) >> LPI2C_MCR_MEN_SHIFT));
  422. LPI2C_MasterEnable(base, false);
  423. base->MCFGR1 = (base->MCFGR1 & ~LPI2C_MCFGR1_MATCFG_MASK) | LPI2C_MCFGR1_MATCFG(matchConfig->matchMode);
  424. base->MCFGR0 = (base->MCFGR0 & ~LPI2C_MCFGR0_RDMO_MASK) | LPI2C_MCFGR0_RDMO(matchConfig->rxDataMatchOnly);
  425. base->MDMR = LPI2C_MDMR_MATCH0(matchConfig->match0) | LPI2C_MDMR_MATCH1(matchConfig->match1);
  426. /* Restore master mode. */
  427. if (wasEnabled)
  428. {
  429. LPI2C_MasterEnable(base, true);
  430. }
  431. }
  432. /*!
  433. * brief Sets the I2C bus frequency for master transactions.
  434. *
  435. * The LPI2C master is automatically disabled and re-enabled as necessary to configure the baud
  436. * rate. Do not call this function during a transfer, or the transfer is aborted.
  437. *
  438. * note Please note that the second parameter is the clock frequency of LPI2C module, the third
  439. * parameter means user configured bus baudrate, this implementation is different from other I2C drivers
  440. * which use baudrate configuration as second parameter and source clock frequency as third parameter.
  441. *
  442. * param base The LPI2C peripheral base address.
  443. * param sourceClock_Hz LPI2C functional clock frequency in Hertz.
  444. * param baudRate_Hz Requested bus frequency in Hertz.
  445. */
  446. void LPI2C_MasterSetBaudRate(LPI2C_Type *base, uint32_t sourceClock_Hz, uint32_t baudRate_Hz)
  447. {
  448. bool wasEnabled;
  449. uint8_t filtScl = (uint8_t)((base->MCFGR2 & LPI2C_MCFGR2_FILTSCL_MASK) >> LPI2C_MCFGR2_FILTSCL_SHIFT);
  450. uint8_t divider = 1U;
  451. uint8_t bestDivider = 1U;
  452. uint8_t prescale = 0U;
  453. uint8_t bestPre = 0U;
  454. uint8_t clkCycle;
  455. uint8_t bestclkCycle = 0U;
  456. uint32_t absError = 0U;
  457. uint32_t bestError = 0xffffffffu;
  458. uint32_t computedRate;
  459. uint32_t tmpReg = 0U;
  460. /* Disable master mode. */
  461. wasEnabled = (0U != ((base->MCR & LPI2C_MCR_MEN_MASK) >> LPI2C_MCR_MEN_SHIFT));
  462. LPI2C_MasterEnable(base, false);
  463. /* Baud rate = (sourceClock_Hz / 2 ^ prescale) / (CLKLO + 1 + CLKHI + 1 + SCL_LATENCY)
  464. * SCL_LATENCY = ROUNDDOWN((2 + FILTSCL) / (2 ^ prescale))
  465. */
  466. for (prescale = 0U; prescale <= 7U; prescale++)
  467. {
  468. /* Calculate the clkCycle, clkCycle = CLKLO + CLKHI, divider = 2 ^ prescale */
  469. clkCycle = (uint8_t)((10U * sourceClock_Hz / divider / baudRate_Hz + 5U) / 10U - (2U + filtScl) / divider - 2U);
  470. /* According to register description, The max value for CLKLO and CLKHI is 63.
  471. however to meet the I2C specification of tBUF, CLKHI should be less than
  472. clkCycle - 0.52 x sourceClock_Hz / baudRate_Hz / divider + 1U. Refer to the comment of the tmpHigh's
  473. calculation for details. So we have:
  474. CLKHI < clkCycle - 0.52 x sourceClock_Hz / baudRate_Hz / divider + 1U,
  475. clkCycle = CLKHI + CLKLO and
  476. sourceClock_Hz / baudRate_Hz / divider = clkCycle + 2 + ROUNDDOWN((2 + FILTSCL) / divider),
  477. we can come up with: CLKHI < 0.92 x CLKLO - ROUNDDOWN(2 + FILTSCL) / divider
  478. so the max boundary of CLKHI should be 0.92 x 63 - ROUNDDOWN(2 + FILTSCL) / divider,
  479. and the max boundary of clkCycle is 1.92 x 63 - ROUNDDOWN(2 + FILTSCL) / divider. */
  480. if (clkCycle > (120U - (2U + filtScl) / divider))
  481. {
  482. divider *= 2U;
  483. continue;
  484. }
  485. /* Calculate the computed baudrate and compare it with the desired baudrate */
  486. computedRate = (sourceClock_Hz / (uint32_t)divider) /
  487. ((uint32_t)clkCycle + 2U + (2U + (uint32_t)filtScl) / (uint32_t)divider);
  488. absError = baudRate_Hz > computedRate ? baudRate_Hz - computedRate : computedRate - baudRate_Hz;
  489. if (absError < bestError)
  490. {
  491. bestPre = prescale;
  492. bestDivider = divider;
  493. bestclkCycle = clkCycle;
  494. bestError = absError;
  495. /* If the error is 0, then we can stop searching because we won't find a better match. */
  496. if (absError == 0U)
  497. {
  498. break;
  499. }
  500. }
  501. divider *= 2U;
  502. }
  503. /* SCL low time tLO should be larger than or equal to SCL high time tHI:
  504. tLO = ((CLKLO + 1) x (2 ^ PRESCALE)) >= tHI = ((CLKHI + 1 + SCL_LATENCY) x (2 ^ PRESCALE)),
  505. which is CLKLO >= CLKHI + (2U + filtScl) / bestDivider.
  506. Also since bestclkCycle = CLKLO + CLKHI, bestDivider = 2 ^ PRESCALE
  507. which makes CLKHI <= (bestclkCycle - (2U + filtScl) / bestDivider) / 2U.
  508. The max tBUF should be at least 0.52 times of the SCL clock cycle:
  509. tBUF = ((CLKLO + 1) x (2 ^ PRESCALE) / sourceClock_Hz) > (0.52 / baudRate_Hz),
  510. plus bestDivider = 2 ^ PRESCALE, bestclkCycle = CLKLO + CLKHI we can come up with
  511. CLKHI <= (bestclkCycle - 0.52 x sourceClock_Hz / baudRate_Hz / bestDivider + 1U).
  512. In this case to get a safe CLKHI calculation, we can assume:
  513. */
  514. uint8_t tmpHigh = (bestclkCycle - (2U + filtScl) / bestDivider) / 2U;
  515. while (tmpHigh > (bestclkCycle - 52U * sourceClock_Hz / baudRate_Hz / bestDivider / 100U + 1U))
  516. {
  517. tmpHigh = tmpHigh - 1U;
  518. }
  519. /* Calculate DATAVD and SETHOLD.
  520. To meet the timing requirement of I2C spec for standard mode, fast mode and fast mode plus: */
  521. /* The min tHD:STA/tSU:STA/tSU:STO should be at least 0.4 times of the SCL clock cycle, use 0.5 to be safe:
  522. tHD:STA = ((SETHOLD + 1) x (2 ^ PRESCALE) / sourceClock_Hz) > (0.5 / baudRate_Hz), bestDivider = 2 ^ PRESCALE */
  523. uint8_t tmpHold = (uint8_t)(sourceClock_Hz / baudRate_Hz / bestDivider / 2U) - 1U;
  524. /* The max tVD:DAT/tVD:ACK/tHD:DAT should be at most 0.345 times of the SCL clock cycle, use 0.25 to be safe:
  525. tVD:DAT = ((DATAVD + 1) x (2 ^ PRESCALE) / sourceClock_Hz) < (0.25 / baudRate_Hz), bestDivider = 2 ^ PRESCALE */
  526. uint8_t tmpDataVd = (uint8_t)(sourceClock_Hz / baudRate_Hz / bestDivider / 4U) - 1U;
  527. /* The min tSU:DAT should be at least 0.05 times of the SCL clock cycle:
  528. tSU:DAT = ((2 + FILTSDA + 2 ^ PRESCALE) / sourceClock_Hz) >= (0.05 / baud),
  529. plus bestDivider = 2 ^ PRESCALE, we can come up with:
  530. FILTSDA >= (0.05 x sourceClock_Hz / baudRate_Hz - bestDivider - 2) */
  531. if ((sourceClock_Hz / baudRate_Hz / 20U) > (bestDivider + 2U))
  532. {
  533. /* Read out the FILTSDA configuration, if it is smaller than expected, change the setting. */
  534. uint8_t filtSda = (uint8_t)((base->MCFGR2 & LPI2C_MCFGR2_FILTSDA_MASK) >> LPI2C_MCFGR2_FILTSDA_SHIFT);
  535. if (filtSda < (sourceClock_Hz / baudRate_Hz / 20U - bestDivider - 2U))
  536. {
  537. filtSda = (uint8_t)(sourceClock_Hz / baudRate_Hz / 20U) - bestDivider - 2U;
  538. }
  539. base->MCFGR2 = (base->MCFGR2 & ~LPI2C_MCFGR2_FILTSDA_MASK) | LPI2C_MCFGR2_FILTSDA(filtSda);
  540. }
  541. /* Set CLKHI, CLKLO, SETHOLD, DATAVD value. */
  542. tmpReg = LPI2C_MCCR0_CLKHI((uint32_t)tmpHigh) |
  543. LPI2C_MCCR0_CLKLO((uint32_t)((uint32_t)bestclkCycle - (uint32_t)tmpHigh)) |
  544. LPI2C_MCCR0_SETHOLD((uint32_t)tmpHold) | LPI2C_MCCR0_DATAVD((uint32_t)tmpDataVd);
  545. base->MCCR0 = tmpReg;
  546. /* Set PRESCALE value. */
  547. base->MCFGR1 = (base->MCFGR1 & ~LPI2C_MCFGR1_PRESCALE_MASK) | LPI2C_MCFGR1_PRESCALE(bestPre);
  548. /* Restore master mode. */
  549. if (wasEnabled)
  550. {
  551. LPI2C_MasterEnable(base, true);
  552. }
  553. }
  554. /*!
  555. * brief Sends a START signal and slave address on the I2C bus.
  556. *
  557. * This function is used to initiate a new master mode transfer. First, the bus state is checked to ensure
  558. * that another master is not occupying the bus. Then a START signal is transmitted, followed by the
  559. * 7-bit address specified in the a address parameter. Note that this function does not actually wait
  560. * until the START and address are successfully sent on the bus before returning.
  561. *
  562. * param base The LPI2C peripheral base address.
  563. * param address 7-bit slave device address, in bits [6:0].
  564. * param dir Master transfer direction, either #kLPI2C_Read or #kLPI2C_Write. This parameter is used to set
  565. * the R/w bit (bit 0) in the transmitted slave address.
  566. * retval #kStatus_Success START signal and address were successfully enqueued in the transmit FIFO.
  567. * retval #kStatus_LPI2C_Busy Another master is currently utilizing the bus.
  568. */
  569. status_t LPI2C_MasterStart(LPI2C_Type *base, uint8_t address, lpi2c_direction_t dir)
  570. {
  571. /* Return an error if the bus is already in use not by us. */
  572. status_t result = LPI2C_CheckForBusyBus(base);
  573. if (kStatus_Success == result)
  574. {
  575. /* Clear all flags. */
  576. LPI2C_MasterClearStatusFlags(base, (uint32_t)kLPI2C_MasterClearFlags);
  577. /* Turn off auto-stop option. */
  578. base->MCFGR1 &= ~LPI2C_MCFGR1_AUTOSTOP_MASK;
  579. /* Wait until there is room in the fifo. */
  580. result = LPI2C_MasterWaitForTxReady(base);
  581. if (kStatus_Success == result)
  582. {
  583. /* Issue start command. */
  584. base->MTDR = (uint32_t)kStartCmd | (((uint32_t)address << 1U) | (uint32_t)dir);
  585. }
  586. }
  587. return result;
  588. }
  589. /*!
  590. * brief Sends a STOP signal on the I2C bus.
  591. *
  592. * This function does not return until the STOP signal is seen on the bus, or an error occurs.
  593. *
  594. * param base The LPI2C peripheral base address.
  595. * retval #kStatus_Success The STOP signal was successfully sent on the bus and the transaction terminated.
  596. * retval #kStatus_LPI2C_Busy Another master is currently utilizing the bus.
  597. * retval #kStatus_LPI2C_Nak The slave device sent a NAK in response to a byte.
  598. * retval #kStatus_LPI2C_FifoError FIFO under run or overrun.
  599. * retval #kStatus_LPI2C_ArbitrationLost Arbitration lost error.
  600. * retval #kStatus_LPI2C_PinLowTimeout SCL or SDA were held low longer than the timeout.
  601. */
  602. status_t LPI2C_MasterStop(LPI2C_Type *base)
  603. {
  604. /* Wait until there is room in the fifo. */
  605. status_t result = LPI2C_MasterWaitForTxReady(base);
  606. if (kStatus_Success == result)
  607. {
  608. /* Send the STOP signal */
  609. base->MTDR = (uint32_t)kStopCmd;
  610. /* Wait for the stop detected flag to set, indicating the transfer has completed on the bus. */
  611. /* Also check for errors while waiting. */
  612. #if I2C_RETRY_TIMES != 0U
  613. uint32_t waitTimes = I2C_RETRY_TIMES;
  614. #endif
  615. #if I2C_RETRY_TIMES != 0U
  616. while ((result == kStatus_Success) && (0U != waitTimes))
  617. {
  618. waitTimes--;
  619. #else
  620. while (result == kStatus_Success)
  621. {
  622. #endif
  623. uint32_t status = LPI2C_MasterGetStatusFlags(base);
  624. /* Check for error flags. */
  625. result = LPI2C_MasterCheckAndClearError(base, status);
  626. /* Check if the stop was sent successfully. */
  627. if ((0U != (status & (uint32_t)kLPI2C_MasterStopDetectFlag)) &&
  628. (0U != (status & (uint32_t)kLPI2C_MasterTxReadyFlag)))
  629. {
  630. LPI2C_MasterClearStatusFlags(base, (uint32_t)kLPI2C_MasterStopDetectFlag);
  631. break;
  632. }
  633. }
  634. #if I2C_RETRY_TIMES != 0U
  635. if (0U == waitTimes)
  636. {
  637. result = kStatus_LPI2C_Timeout;
  638. }
  639. #endif
  640. }
  641. return result;
  642. }
  643. /*!
  644. * brief Performs a polling receive transfer on the I2C bus.
  645. *
  646. * param base The LPI2C peripheral base address.
  647. * param rxBuff The pointer to the data to be transferred.
  648. * param rxSize The length in bytes of the data to be transferred.
  649. * retval #kStatus_Success Data was received successfully.
  650. * retval #kStatus_LPI2C_Busy Another master is currently utilizing the bus.
  651. * retval #kStatus_LPI2C_Nak The slave device sent a NAK in response to a byte.
  652. * retval #kStatus_LPI2C_FifoError FIFO under run or overrun.
  653. * retval #kStatus_LPI2C_ArbitrationLost Arbitration lost error.
  654. * retval #kStatus_LPI2C_PinLowTimeout SCL or SDA were held low longer than the timeout.
  655. */
  656. status_t LPI2C_MasterReceive(LPI2C_Type *base, void *rxBuff, size_t rxSize)
  657. {
  658. assert(NULL != rxBuff);
  659. status_t result = kStatus_Success;
  660. uint8_t *buf;
  661. size_t tmpRxSize = rxSize;
  662. #if I2C_RETRY_TIMES != 0U
  663. uint32_t waitTimes;
  664. #endif
  665. /* Check transfer data size. */
  666. if (rxSize > (256UL * (uint32_t)FSL_FEATURE_LPI2C_FIFO_SIZEn(base)))
  667. {
  668. return kStatus_InvalidArgument;
  669. }
  670. /* Handle empty read. */
  671. if (rxSize != 0U)
  672. {
  673. /* Wait until there is room in the command fifo. */
  674. result = LPI2C_MasterWaitForTxReady(base);
  675. if (kStatus_Success == result)
  676. {
  677. /* Issue command to receive data. A single write to MTDR can issue read operation of 0xFFU + 1 byte of data
  678. at most, so when the rxSize is larger than 0x100U, push multiple read commands to MTDR until rxSize is
  679. reached. */
  680. while (tmpRxSize != 0U)
  681. {
  682. if (tmpRxSize > 256U)
  683. {
  684. base->MTDR = (uint32_t)(kRxDataCmd) | (uint32_t)LPI2C_MTDR_DATA(0xFFU);
  685. tmpRxSize -= 256U;
  686. }
  687. else
  688. {
  689. base->MTDR = (uint32_t)(kRxDataCmd) | (uint32_t)LPI2C_MTDR_DATA(tmpRxSize - 1U);
  690. tmpRxSize = 0U;
  691. }
  692. }
  693. /* Receive data */
  694. buf = (uint8_t *)rxBuff;
  695. while (0U != (rxSize--))
  696. {
  697. #if I2C_RETRY_TIMES != 0U
  698. waitTimes = I2C_RETRY_TIMES;
  699. #endif
  700. /* Read LPI2C receive fifo register. The register includes a flag to indicate whether */
  701. /* the FIFO is empty, so we can both get the data and check if we need to keep reading */
  702. /* using a single register read. */
  703. uint32_t value = 0U;
  704. do
  705. {
  706. /* Check for errors. */
  707. result = LPI2C_MasterCheckAndClearError(base, LPI2C_MasterGetStatusFlags(base));
  708. if (kStatus_Success != result)
  709. {
  710. break;
  711. }
  712. value = base->MRDR;
  713. #if I2C_RETRY_TIMES != 0U
  714. waitTimes--;
  715. } while ((0U != (value & LPI2C_MRDR_RXEMPTY_MASK)) && (0U != waitTimes));
  716. if (0U == waitTimes)
  717. {
  718. result = kStatus_LPI2C_Timeout;
  719. }
  720. #else
  721. } while (0U != (value & LPI2C_MRDR_RXEMPTY_MASK));
  722. #endif
  723. if ((status_t)kStatus_Success != result)
  724. {
  725. break;
  726. }
  727. *buf++ = (uint8_t)(value & LPI2C_MRDR_DATA_MASK);
  728. }
  729. }
  730. }
  731. return result;
  732. }
  733. /*!
  734. * brief Performs a polling send transfer on the I2C bus.
  735. *
  736. * Sends up to a txSize number of bytes to the previously addressed slave device. The slave may
  737. * reply with a NAK to any byte in order to terminate the transfer early. If this happens, this
  738. * function returns #kStatus_LPI2C_Nak.
  739. *
  740. * param base The LPI2C peripheral base address.
  741. * param txBuff The pointer to the data to be transferred.
  742. * param txSize The length in bytes of the data to be transferred.
  743. * retval #kStatus_Success Data was sent successfully.
  744. * retval #kStatus_LPI2C_Busy Another master is currently utilizing the bus.
  745. * retval #kStatus_LPI2C_Nak The slave device sent a NAK in response to a byte.
  746. * retval #kStatus_LPI2C_FifoError FIFO under run or over run.
  747. * retval #kStatus_LPI2C_ArbitrationLost Arbitration lost error.
  748. * retval #kStatus_LPI2C_PinLowTimeout SCL or SDA were held low longer than the timeout.
  749. */
  750. status_t LPI2C_MasterSend(LPI2C_Type *base, void *txBuff, size_t txSize)
  751. {
  752. status_t result = kStatus_Success;
  753. uint8_t *buf = (uint8_t *)txBuff;
  754. assert(NULL != txBuff);
  755. /* Send data buffer */
  756. while (0U != (txSize--))
  757. {
  758. /* Wait until there is room in the fifo. This also checks for errors. */
  759. result = LPI2C_MasterWaitForTxReady(base);
  760. if (kStatus_Success != result)
  761. {
  762. break;
  763. }
  764. /* Write byte into LPI2C master data register. */
  765. base->MTDR = *buf++;
  766. }
  767. return result;
  768. }
  769. /*!
  770. * brief Performs a master polling transfer on the I2C bus.
  771. *
  772. * note The API does not return until the transfer succeeds or fails due
  773. * to error happens during transfer.
  774. *
  775. * param base The LPI2C peripheral base address.
  776. * param transfer Pointer to the transfer structure.
  777. * retval #kStatus_Success Data was received successfully.
  778. * retval #kStatus_LPI2C_Busy Another master is currently utilizing the bus.
  779. * retval #kStatus_LPI2C_Nak The slave device sent a NAK in response to a byte.
  780. * retval #kStatus_LPI2C_FifoError FIFO under run or overrun.
  781. * retval #kStatus_LPI2C_ArbitrationLost Arbitration lost error.
  782. * retval #kStatus_LPI2C_PinLowTimeout SCL or SDA were held low longer than the timeout.
  783. */
  784. status_t LPI2C_MasterTransferBlocking(LPI2C_Type *base, lpi2c_master_transfer_t *transfer)
  785. {
  786. assert(NULL != transfer);
  787. assert(transfer->subaddressSize <= sizeof(transfer->subaddress));
  788. status_t result = kStatus_Success;
  789. uint16_t commandBuffer[7];
  790. uint32_t cmdCount = 0U;
  791. /* Check transfer data size in read operation. */
  792. if ((transfer->direction == kLPI2C_Read) &&
  793. (transfer->dataSize > (256UL * (uint32_t)FSL_FEATURE_LPI2C_FIFO_SIZEn(base))))
  794. {
  795. return kStatus_InvalidArgument;
  796. }
  797. /* Return an error if the bus is already in use not by us. */
  798. result = LPI2C_CheckForBusyBus(base);
  799. if (kStatus_Success == result)
  800. {
  801. /* Clear all flags. */
  802. LPI2C_MasterClearStatusFlags(base, (uint32_t)kLPI2C_MasterClearFlags);
  803. /* Turn off auto-stop option. */
  804. base->MCFGR1 &= ~LPI2C_MCFGR1_AUTOSTOP_MASK;
  805. lpi2c_direction_t direction = (0U != transfer->subaddressSize) ? kLPI2C_Write : transfer->direction;
  806. if (0U == (transfer->flags & (uint32_t)kLPI2C_TransferNoStartFlag))
  807. {
  808. commandBuffer[cmdCount++] =
  809. (uint16_t)kStartCmd |
  810. (uint16_t)((uint16_t)((uint16_t)transfer->slaveAddress << 1U) | (uint16_t)direction);
  811. }
  812. /* Subaddress, MSB first. */
  813. if (0U != transfer->subaddressSize)
  814. {
  815. uint32_t subaddressRemaining = transfer->subaddressSize;
  816. while (0U != subaddressRemaining--)
  817. {
  818. uint8_t subaddressByte = (uint8_t)((transfer->subaddress >> (8U * subaddressRemaining)) & 0xffU);
  819. commandBuffer[cmdCount++] = subaddressByte;
  820. }
  821. }
  822. /* Reads need special handling. */
  823. if ((0U != transfer->dataSize) && (transfer->direction == kLPI2C_Read))
  824. {
  825. /* Need to send repeated start if switching directions to read. */
  826. if (direction == kLPI2C_Write)
  827. {
  828. commandBuffer[cmdCount++] =
  829. (uint16_t)kStartCmd |
  830. (uint16_t)((uint16_t)((uint16_t)transfer->slaveAddress << 1U) | (uint16_t)kLPI2C_Read);
  831. }
  832. }
  833. /* Send command buffer */
  834. uint32_t index = 0U;
  835. while (0U != cmdCount--)
  836. {
  837. /* Wait until there is room in the fifo. This also checks for errors. */
  838. result = LPI2C_MasterWaitForTxReady(base);
  839. if (kStatus_Success != result)
  840. {
  841. break;
  842. }
  843. /* Write byte into LPI2C master data register. */
  844. base->MTDR = commandBuffer[index];
  845. index++;
  846. }
  847. if (kStatus_Success == result)
  848. {
  849. /* Transmit data. */
  850. if ((transfer->direction == kLPI2C_Write) && (transfer->dataSize > 0U))
  851. {
  852. /* Send Data. */
  853. result = LPI2C_MasterSend(base, transfer->data, transfer->dataSize);
  854. }
  855. /* Receive Data. */
  856. if ((transfer->direction == kLPI2C_Read) && (transfer->dataSize > 0U))
  857. {
  858. result = LPI2C_MasterReceive(base, transfer->data, transfer->dataSize);
  859. }
  860. if (kStatus_Success == result)
  861. {
  862. if ((transfer->flags & (uint32_t)kLPI2C_TransferNoStopFlag) == 0U)
  863. {
  864. result = LPI2C_MasterStop(base);
  865. }
  866. }
  867. }
  868. }
  869. return result;
  870. }
  871. /*!
  872. * brief Creates a new handle for the LPI2C master non-blocking APIs.
  873. *
  874. * The creation of a handle is for use with the non-blocking APIs. Once a handle
  875. * is created, there is not a corresponding destroy handle. If the user wants to
  876. * terminate a transfer, the LPI2C_MasterTransferAbort() API shall be called.
  877. *
  878. *
  879. * note The function also enables the NVIC IRQ for the input LPI2C. Need to notice
  880. * that on some SoCs the LPI2C IRQ is connected to INTMUX, in this case user needs to
  881. * enable the associated INTMUX IRQ in application.
  882. *
  883. * param base The LPI2C peripheral base address.
  884. * param[out] handle Pointer to the LPI2C master driver handle.
  885. * param callback User provided pointer to the asynchronous callback function.
  886. * param userData User provided pointer to the application callback data.
  887. */
  888. void LPI2C_MasterTransferCreateHandle(LPI2C_Type *base,
  889. lpi2c_master_handle_t *handle,
  890. lpi2c_master_transfer_callback_t callback,
  891. void *userData)
  892. {
  893. uint32_t instance;
  894. assert(NULL != handle);
  895. /* Clear out the handle. */
  896. (void)memset(handle, 0, sizeof(*handle));
  897. /* Look up instance number */
  898. instance = LPI2C_GetInstance(base);
  899. /* Save base and instance. */
  900. handle->completionCallback = callback;
  901. handle->userData = userData;
  902. /* Save this handle for IRQ use. */
  903. s_lpi2cMasterHandle[instance] = handle;
  904. /* Set irq handler. */
  905. s_lpi2cMasterIsr = LPI2C_MasterTransferHandleIRQ;
  906. /* Clear internal IRQ enables and enable NVIC IRQ. */
  907. LPI2C_MasterDisableInterrupts(base, (uint32_t)kLPI2C_MasterIrqFlags);
  908. /* Enable NVIC IRQ, this only enables the IRQ directly connected to the NVIC.
  909. In some cases the LPI2C IRQ is configured through INTMUX, user needs to enable
  910. INTMUX IRQ in application code. */
  911. (void)EnableIRQ(kLpi2cIrqs[instance]);
  912. }
  913. /*!
  914. * @brief Execute states until FIFOs are exhausted.
  915. * @param handle Master nonblocking driver handle.
  916. * @param[out] isDone Set to true if the transfer has completed.
  917. * @retval #kStatus_Success
  918. * @retval #kStatus_LPI2C_PinLowTimeout
  919. * @retval #kStatus_LPI2C_ArbitrationLost
  920. * @retval #kStatus_LPI2C_Nak
  921. * @retval #kStatus_LPI2C_FifoError
  922. */
  923. static status_t LPI2C_RunTransferStateMachine(LPI2C_Type *base, lpi2c_master_handle_t *handle, bool *isDone)
  924. {
  925. uint32_t status;
  926. status_t result = kStatus_Success;
  927. lpi2c_master_transfer_t *xfer;
  928. size_t txCount;
  929. size_t rxCount;
  930. size_t txFifoSize = (size_t)FSL_FEATURE_LPI2C_FIFO_SIZEn(base);
  931. bool state_complete = false;
  932. uint16_t sendval;
  933. /* Set default isDone return value. */
  934. *isDone = false;
  935. /* Check for errors. */
  936. status = LPI2C_MasterGetStatusFlags(base);
  937. /* Get fifo counts. */
  938. LPI2C_MasterGetFifoCounts(base, &rxCount, &txCount);
  939. /* Get pointer to private data. */
  940. xfer = &handle->transfer;
  941. /* For the last byte, nack flag is expected.
  942. Do not check and clear kLPI2C_MasterNackDetectFlag for the last byte,
  943. in case FIFO is emptied when stop command has not been sent. */
  944. if (handle->remainingBytes == 0U)
  945. {
  946. /* When data size is not zero which means it is not only one byte of address is sent, and */
  947. /* when the txfifo is empty, or have one byte which is the stop command, then the nack status can be ignored. */
  948. if ((xfer->dataSize != 0U) &&
  949. ((txCount == 0U) || ((txCount == 1U) && (handle->state == (uint8_t)kWaitForCompletionState) &&
  950. ((xfer->flags & (uint32_t)kLPI2C_TransferNoStopFlag) == 0U))))
  951. {
  952. status &= ~(uint32_t)kLPI2C_MasterNackDetectFlag;
  953. }
  954. }
  955. result = LPI2C_MasterCheckAndClearError(base, status);
  956. if (kStatus_Success == result)
  957. {
  958. /* Compute room in tx fifo */
  959. txCount = txFifoSize - txCount;
  960. while (!state_complete)
  961. {
  962. /* Execute the state. */
  963. switch (handle->state)
  964. {
  965. case (uint8_t)kSendCommandState:
  966. /* Make sure there is room in the tx fifo for the next command. */
  967. if (0U == txCount--)
  968. {
  969. state_complete = true;
  970. break;
  971. }
  972. /* Issue command. buf is a uint8_t* pointing at the uint16 command array. */
  973. sendval = ((uint16_t)handle->buf[0]) | (((uint16_t)handle->buf[1]) << 8U);
  974. base->MTDR = sendval;
  975. handle->buf++;
  976. handle->buf++;
  977. /* Count down until all commands are sent. */
  978. if (--handle->remainingBytes == 0U)
  979. {
  980. /* Choose next state and set up buffer pointer and count. */
  981. if (0U != xfer->dataSize)
  982. {
  983. /* Either a send or receive transfer is next. */
  984. handle->state = (uint8_t)kTransferDataState;
  985. handle->buf = (uint8_t *)xfer->data;
  986. handle->remainingBytes = (uint16_t)xfer->dataSize;
  987. if (xfer->direction == kLPI2C_Read)
  988. {
  989. /* Disable TX interrupt */
  990. LPI2C_MasterDisableInterrupts(base, (uint32_t)kLPI2C_MasterTxReadyFlag);
  991. /* Issue command to receive data. A single write to MTDR can issue read operation of
  992. 0xFFU + 1 byte of data at most, so when the dataSize is larger than 0x100U, push
  993. multiple read commands to MTDR until dataSize is reached. */
  994. size_t tmpRxSize = xfer->dataSize;
  995. while (tmpRxSize != 0U)
  996. {
  997. LPI2C_MasterGetFifoCounts(base, NULL, &txCount);
  998. while (txFifoSize == txCount)
  999. {
  1000. LPI2C_MasterGetFifoCounts(base, NULL, &txCount);
  1001. }
  1002. if (tmpRxSize > 256U)
  1003. {
  1004. base->MTDR = (uint32_t)(kRxDataCmd) | (uint32_t)LPI2C_MTDR_DATA(0xFFU);
  1005. tmpRxSize -= 256U;
  1006. }
  1007. else
  1008. {
  1009. base->MTDR = (uint32_t)(kRxDataCmd) | (uint32_t)LPI2C_MTDR_DATA(tmpRxSize - 1U);
  1010. tmpRxSize = 0U;
  1011. }
  1012. }
  1013. }
  1014. }
  1015. else
  1016. {
  1017. /* No transfer, so move to stop state. */
  1018. handle->state = (uint8_t)kStopState;
  1019. }
  1020. }
  1021. break;
  1022. case (uint8_t)kIssueReadCommandState:
  1023. /* Make sure there is room in the tx fifo for the read command. */
  1024. if (0U == txCount--)
  1025. {
  1026. state_complete = true;
  1027. break;
  1028. }
  1029. base->MTDR = (uint32_t)kRxDataCmd | LPI2C_MTDR_DATA(xfer->dataSize - 1U);
  1030. /* Move to transfer state. */
  1031. handle->state = (uint8_t)kTransferDataState;
  1032. if (xfer->direction == kLPI2C_Read)
  1033. {
  1034. /* Disable TX interrupt */
  1035. LPI2C_MasterDisableInterrupts(base, (uint32_t)kLPI2C_MasterTxReadyFlag);
  1036. }
  1037. break;
  1038. case (uint8_t)kTransferDataState:
  1039. if (xfer->direction == kLPI2C_Write)
  1040. {
  1041. /* Make sure there is room in the tx fifo. */
  1042. if (0U == txCount--)
  1043. {
  1044. state_complete = true;
  1045. break;
  1046. }
  1047. /* Put byte to send in fifo. */
  1048. base->MTDR = *(handle->buf)++;
  1049. }
  1050. else
  1051. {
  1052. /* XXX handle receive sizes > 256, use kIssueReadCommandState */
  1053. /* Make sure there is data in the rx fifo. */
  1054. if (0U == rxCount--)
  1055. {
  1056. state_complete = true;
  1057. break;
  1058. }
  1059. /* Read byte from fifo. */
  1060. *(handle->buf)++ = (uint8_t)(base->MRDR & LPI2C_MRDR_DATA_MASK);
  1061. }
  1062. /* Move to stop when the transfer is done. */
  1063. if (--handle->remainingBytes == 0U)
  1064. {
  1065. if (xfer->direction == kLPI2C_Write)
  1066. {
  1067. state_complete = true;
  1068. }
  1069. handle->state = (uint8_t)kStopState;
  1070. }
  1071. break;
  1072. case (uint8_t)kStopState:
  1073. /* Only issue a stop transition if the caller requested it. */
  1074. if ((xfer->flags & (uint32_t)kLPI2C_TransferNoStopFlag) == 0U)
  1075. {
  1076. /* Make sure there is room in the tx fifo for the stop command. */
  1077. if (0U == txCount--)
  1078. {
  1079. state_complete = true;
  1080. break;
  1081. }
  1082. base->MTDR = (uint32_t)kStopCmd;
  1083. }
  1084. else
  1085. {
  1086. /* If all data is read and no stop flag is required to send, we are done. */
  1087. if (xfer->direction == kLPI2C_Read)
  1088. {
  1089. *isDone = true;
  1090. }
  1091. state_complete = true;
  1092. }
  1093. handle->state = (uint8_t)kWaitForCompletionState;
  1094. break;
  1095. case (uint8_t)kWaitForCompletionState:
  1096. if ((xfer->flags & (uint32_t)kLPI2C_TransferNoStopFlag) == 0U)
  1097. {
  1098. /* We stay in this state until the stop state is detected. */
  1099. if (0U != (status & (uint32_t)kLPI2C_MasterStopDetectFlag))
  1100. {
  1101. *isDone = true;
  1102. }
  1103. }
  1104. else
  1105. {
  1106. /* If all data is pushed to FIFO and no stop flag is required to send, we need to make sure they
  1107. are all send out to bus. */
  1108. if ((xfer->direction == kLPI2C_Write) && ((base->MFSR & LPI2C_MFSR_TXCOUNT_MASK) == 0U))
  1109. {
  1110. /* We stay in this state until the data is sent out to bus. */
  1111. *isDone = true;
  1112. }
  1113. }
  1114. state_complete = true;
  1115. break;
  1116. default:
  1117. assert(false);
  1118. break;
  1119. }
  1120. }
  1121. }
  1122. return result;
  1123. }
  1124. /*!
  1125. * @brief Prepares the transfer state machine and fills in the command buffer.
  1126. * @param handle Master nonblocking driver handle.
  1127. */
  1128. static void LPI2C_InitTransferStateMachine(lpi2c_master_handle_t *handle)
  1129. {
  1130. lpi2c_master_transfer_t *xfer = &handle->transfer;
  1131. /* Handle no start option. */
  1132. if (0U != (xfer->flags & (uint32_t)kLPI2C_TransferNoStartFlag))
  1133. {
  1134. if (xfer->direction == kLPI2C_Read)
  1135. {
  1136. /* Need to issue read command first. */
  1137. handle->state = (uint8_t)kIssueReadCommandState;
  1138. }
  1139. else
  1140. {
  1141. /* Start immediately in the data transfer state. */
  1142. handle->state = (uint8_t)kTransferDataState;
  1143. }
  1144. handle->buf = (uint8_t *)xfer->data;
  1145. handle->remainingBytes = (uint16_t)xfer->dataSize;
  1146. }
  1147. else
  1148. {
  1149. uint16_t *cmd = (uint16_t *)&handle->commandBuffer;
  1150. uint32_t cmdCount = 0U;
  1151. /* Initial direction depends on whether a subaddress was provided, and of course the actual */
  1152. /* data transfer direction. */
  1153. lpi2c_direction_t direction = (0U != xfer->subaddressSize) ? kLPI2C_Write : xfer->direction;
  1154. /* Start command. */
  1155. cmd[cmdCount++] =
  1156. (uint16_t)kStartCmd | (uint16_t)((uint16_t)((uint16_t)xfer->slaveAddress << 1U) | (uint16_t)direction);
  1157. /* Subaddress, MSB first. */
  1158. if (0U != xfer->subaddressSize)
  1159. {
  1160. uint32_t subaddressRemaining = xfer->subaddressSize;
  1161. while (0U != (subaddressRemaining--))
  1162. {
  1163. uint8_t subaddressByte = (uint8_t)((xfer->subaddress >> (8U * subaddressRemaining)) & 0xffU);
  1164. cmd[cmdCount++] = subaddressByte;
  1165. }
  1166. }
  1167. /* Reads need special handling. */
  1168. if ((0U != xfer->dataSize) && (xfer->direction == kLPI2C_Read))
  1169. {
  1170. /* Need to send repeated start if switching directions to read. */
  1171. if (direction == kLPI2C_Write)
  1172. {
  1173. cmd[cmdCount++] = (uint16_t)kStartCmd |
  1174. (uint16_t)((uint16_t)((uint16_t)xfer->slaveAddress << 1U) | (uint16_t)kLPI2C_Read);
  1175. }
  1176. }
  1177. /* Set up state machine for transferring the commands. */
  1178. handle->state = (uint8_t)kSendCommandState;
  1179. handle->remainingBytes = (uint16_t)cmdCount;
  1180. handle->buf = (uint8_t *)&handle->commandBuffer;
  1181. }
  1182. }
  1183. /*!
  1184. * brief Performs a non-blocking transaction on the I2C bus.
  1185. *
  1186. * param base The LPI2C peripheral base address.
  1187. * param handle Pointer to the LPI2C master driver handle.
  1188. * param transfer The pointer to the transfer descriptor.
  1189. * retval #kStatus_Success The transaction was started successfully.
  1190. * retval #kStatus_LPI2C_Busy Either another master is currently utilizing the bus, or a non-blocking
  1191. * transaction is already in progress.
  1192. */
  1193. status_t LPI2C_MasterTransferNonBlocking(LPI2C_Type *base,
  1194. lpi2c_master_handle_t *handle,
  1195. lpi2c_master_transfer_t *transfer)
  1196. {
  1197. assert(NULL != handle);
  1198. assert(NULL != transfer);
  1199. assert(transfer->subaddressSize <= sizeof(transfer->subaddress));
  1200. status_t result;
  1201. /* Check transfer data size in read operation. */
  1202. if ((transfer->direction == kLPI2C_Read) &&
  1203. (transfer->dataSize > (256U * (uint32_t)FSL_FEATURE_LPI2C_FIFO_SIZEn(base))))
  1204. {
  1205. return kStatus_InvalidArgument;
  1206. }
  1207. /* Return busy if another transaction is in progress. */
  1208. if (handle->state != (uint8_t)kIdleState)
  1209. {
  1210. result = kStatus_LPI2C_Busy;
  1211. }
  1212. else
  1213. {
  1214. result = LPI2C_CheckForBusyBus(base);
  1215. }
  1216. if ((status_t)kStatus_Success == result)
  1217. {
  1218. /* Disable LPI2C IRQ sources while we configure stuff. */
  1219. LPI2C_MasterDisableInterrupts(base, (uint32_t)kLPI2C_MasterIrqFlags);
  1220. /* Reset FIFO in case there are data. */
  1221. base->MCR |= LPI2C_MCR_RRF_MASK | LPI2C_MCR_RTF_MASK;
  1222. /* Save transfer into handle. */
  1223. handle->transfer = *transfer;
  1224. /* Generate commands to send. */
  1225. LPI2C_InitTransferStateMachine(handle);
  1226. /* Clear all flags. */
  1227. LPI2C_MasterClearStatusFlags(base, (uint32_t)kLPI2C_MasterClearFlags);
  1228. /* Turn off auto-stop option. */
  1229. base->MCFGR1 &= ~LPI2C_MCFGR1_AUTOSTOP_MASK;
  1230. /* Enable LPI2C internal IRQ sources. NVIC IRQ was enabled in CreateHandle() */
  1231. LPI2C_MasterEnableInterrupts(base, (uint32_t)kLPI2C_MasterIrqFlags);
  1232. }
  1233. return result;
  1234. }
  1235. /*!
  1236. * brief Returns number of bytes transferred so far.
  1237. * param base The LPI2C peripheral base address.
  1238. * param handle Pointer to the LPI2C master driver handle.
  1239. * param[out] count Number of bytes transferred so far by the non-blocking transaction.
  1240. * retval #kStatus_Success
  1241. * retval #kStatus_NoTransferInProgress There is not a non-blocking transaction currently in progress.
  1242. */
  1243. status_t LPI2C_MasterTransferGetCount(LPI2C_Type *base, lpi2c_master_handle_t *handle, size_t *count)
  1244. {
  1245. status_t result = kStatus_Success;
  1246. assert(NULL != handle);
  1247. if (NULL == count)
  1248. {
  1249. result = kStatus_InvalidArgument;
  1250. }
  1251. /* Catch when there is not an active transfer. */
  1252. else if (handle->state == (uint8_t)kIdleState)
  1253. {
  1254. *count = 0;
  1255. result = kStatus_NoTransferInProgress;
  1256. }
  1257. else
  1258. {
  1259. uint8_t state;
  1260. uint16_t remainingBytes;
  1261. uint32_t dataSize;
  1262. /* Cache some fields with IRQs disabled. This ensures all field values */
  1263. /* are synchronized with each other during an ongoing transfer. */
  1264. uint32_t irqs = LPI2C_MasterGetEnabledInterrupts(base);
  1265. LPI2C_MasterDisableInterrupts(base, irqs);
  1266. state = handle->state;
  1267. remainingBytes = handle->remainingBytes;
  1268. dataSize = handle->transfer.dataSize;
  1269. LPI2C_MasterEnableInterrupts(base, irqs);
  1270. /* Get transfer count based on current transfer state. */
  1271. switch (state)
  1272. {
  1273. case (uint8_t)kIdleState:
  1274. case (uint8_t)kSendCommandState:
  1275. case (uint8_t)
  1276. kIssueReadCommandState: /* XXX return correct value for this state when >256 reads are supported */
  1277. *count = 0;
  1278. break;
  1279. case (uint8_t)kTransferDataState:
  1280. *count = dataSize - remainingBytes;
  1281. break;
  1282. case (uint8_t)kStopState:
  1283. case (uint8_t)kWaitForCompletionState:
  1284. default:
  1285. *count = dataSize;
  1286. break;
  1287. }
  1288. }
  1289. return result;
  1290. }
  1291. /*!
  1292. * brief Terminates a non-blocking LPI2C master transmission early.
  1293. *
  1294. * note It is not safe to call this function from an IRQ handler that has a higher priority than the
  1295. * LPI2C peripheral's IRQ priority.
  1296. *
  1297. * param base The LPI2C peripheral base address.
  1298. * param handle Pointer to the LPI2C master driver handle.
  1299. * retval #kStatus_Success A transaction was successfully aborted.
  1300. * retval #kStatus_LPI2C_Idle There is not a non-blocking transaction currently in progress.
  1301. */
  1302. void LPI2C_MasterTransferAbort(LPI2C_Type *base, lpi2c_master_handle_t *handle)
  1303. {
  1304. if (handle->state != (uint8_t)kIdleState)
  1305. {
  1306. /* Disable internal IRQ enables. */
  1307. LPI2C_MasterDisableInterrupts(base, (uint32_t)kLPI2C_MasterIrqFlags);
  1308. /* Reset fifos. */
  1309. base->MCR |= LPI2C_MCR_RRF_MASK | LPI2C_MCR_RTF_MASK;
  1310. /* If master is still busy and has not send out stop signal yet. */
  1311. if ((LPI2C_MasterGetStatusFlags(base) & ((uint32_t)kLPI2C_MasterStopDetectFlag |
  1312. (uint32_t)kLPI2C_MasterBusyFlag)) == (uint32_t)kLPI2C_MasterBusyFlag)
  1313. {
  1314. /* Send a stop command to finalize the transfer. */
  1315. base->MTDR = (uint32_t)kStopCmd;
  1316. }
  1317. /* Reset handle. */
  1318. handle->state = (uint8_t)kIdleState;
  1319. }
  1320. }
  1321. /*!
  1322. * brief Reusable routine to handle master interrupts.
  1323. * note This function does not need to be called unless you are reimplementing the
  1324. * nonblocking API's interrupt handler routines to add special functionality.
  1325. * param base The LPI2C peripheral base address.
  1326. * param lpi2cMasterHandle Pointer to the LPI2C master driver handle.
  1327. */
  1328. void LPI2C_MasterTransferHandleIRQ(LPI2C_Type *base, void *lpi2cMasterHandle)
  1329. {
  1330. assert(lpi2cMasterHandle != NULL);
  1331. lpi2c_master_handle_t *handle = (lpi2c_master_handle_t *)lpi2cMasterHandle;
  1332. bool isDone = false;
  1333. status_t result;
  1334. /* Don't do anything if we don't have a valid handle. */
  1335. if (NULL != handle)
  1336. {
  1337. if (handle->state != (uint8_t)kIdleState)
  1338. {
  1339. result = LPI2C_RunTransferStateMachine(base, handle, &isDone);
  1340. if ((result != kStatus_Success) || isDone)
  1341. {
  1342. /* Handle error, terminate xfer */
  1343. if (result != kStatus_Success)
  1344. {
  1345. LPI2C_MasterTransferAbort(base, handle);
  1346. }
  1347. /* Disable internal IRQ enables. */
  1348. LPI2C_MasterDisableInterrupts(base, (uint32_t)kLPI2C_MasterIrqFlags);
  1349. /* Set handle to idle state. */
  1350. handle->state = (uint8_t)kIdleState;
  1351. /* Invoke callback. */
  1352. if (NULL != handle->completionCallback)
  1353. {
  1354. handle->completionCallback(base, handle, result, handle->userData);
  1355. }
  1356. }
  1357. }
  1358. }
  1359. }
  1360. /*!
  1361. * brief Provides a default configuration for the LPI2C slave peripheral.
  1362. *
  1363. * This function provides the following default configuration for the LPI2C slave peripheral:
  1364. * code
  1365. * slaveConfig->enableSlave = true;
  1366. * slaveConfig->address0 = 0U;
  1367. * slaveConfig->address1 = 0U;
  1368. * slaveConfig->addressMatchMode = kLPI2C_MatchAddress0;
  1369. * slaveConfig->filterDozeEnable = true;
  1370. * slaveConfig->filterEnable = true;
  1371. * slaveConfig->enableGeneralCall = false;
  1372. * slaveConfig->sclStall.enableAck = false;
  1373. * slaveConfig->sclStall.enableTx = true;
  1374. * slaveConfig->sclStall.enableRx = true;
  1375. * slaveConfig->sclStall.enableAddress = true;
  1376. * slaveConfig->ignoreAck = false;
  1377. * slaveConfig->enableReceivedAddressRead = false;
  1378. * slaveConfig->sdaGlitchFilterWidth_ns = 0;
  1379. * slaveConfig->sclGlitchFilterWidth_ns = 0;
  1380. * slaveConfig->dataValidDelay_ns = 0;
  1381. * slaveConfig->clockHoldTime_ns = 0;
  1382. * endcode
  1383. *
  1384. * After calling this function, override any settings to customize the configuration,
  1385. * prior to initializing the master driver with LPI2C_SlaveInit(). Be sure to override at least the a
  1386. * address0 member of the configuration structure with the desired slave address.
  1387. *
  1388. * param[out] slaveConfig User provided configuration structure that is set to default values. Refer to
  1389. * #lpi2c_slave_config_t.
  1390. */
  1391. void LPI2C_SlaveGetDefaultConfig(lpi2c_slave_config_t *slaveConfig)
  1392. {
  1393. /* Initializes the configure structure to zero. */
  1394. (void)memset(slaveConfig, 0, sizeof(*slaveConfig));
  1395. slaveConfig->enableSlave = true;
  1396. slaveConfig->address0 = 0U;
  1397. slaveConfig->address1 = 0U;
  1398. slaveConfig->addressMatchMode = kLPI2C_MatchAddress0;
  1399. slaveConfig->filterDozeEnable = true;
  1400. slaveConfig->filterEnable = true;
  1401. slaveConfig->enableGeneralCall = false;
  1402. slaveConfig->sclStall.enableAck = false;
  1403. slaveConfig->sclStall.enableTx = true;
  1404. slaveConfig->sclStall.enableRx = true;
  1405. slaveConfig->sclStall.enableAddress = false;
  1406. slaveConfig->ignoreAck = false;
  1407. slaveConfig->enableReceivedAddressRead = false;
  1408. slaveConfig->sdaGlitchFilterWidth_ns = 0U; /* Set to 0 to disable the function */
  1409. slaveConfig->sclGlitchFilterWidth_ns = 0U; /* Set to 0 to disable the function */
  1410. slaveConfig->dataValidDelay_ns = 0U;
  1411. /* When enabling the slave tx SCL stall, set the default clock hold time to 250ns according
  1412. to I2C spec for standard mode baudrate(100k). User can manually change it to 100ns or 50ns
  1413. for fast-mode(400k) or fast-mode+(1m). */
  1414. slaveConfig->clockHoldTime_ns = 250U;
  1415. }
  1416. /*!
  1417. * brief Initializes the LPI2C slave peripheral.
  1418. *
  1419. * This function enables the peripheral clock and initializes the LPI2C slave peripheral as described by the user
  1420. * provided configuration.
  1421. *
  1422. * param base The LPI2C peripheral base address.
  1423. * param slaveConfig User provided peripheral configuration. Use LPI2C_SlaveGetDefaultConfig() to get a set of defaults
  1424. * that you can override.
  1425. * param sourceClock_Hz Frequency in Hertz of the LPI2C functional clock. Used to calculate the filter widths,
  1426. * data valid delay, and clock hold time.
  1427. */
  1428. void LPI2C_SlaveInit(LPI2C_Type *base, const lpi2c_slave_config_t *slaveConfig, uint32_t sourceClock_Hz)
  1429. {
  1430. uint32_t tmpReg;
  1431. uint32_t tmpCycle;
  1432. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  1433. uint32_t instance = LPI2C_GetInstance(base);
  1434. /* Ungate the clock. */
  1435. (void)CLOCK_EnableClock(kLpi2cClocks[instance]);
  1436. #if defined(LPI2C_PERIPH_CLOCKS)
  1437. /* Ungate the functional clock in initialize function. */
  1438. CLOCK_EnableClock(kLpi2cPeriphClocks[instance]);
  1439. #endif
  1440. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  1441. /* Restore to reset conditions. */
  1442. LPI2C_SlaveReset(base);
  1443. /* Configure peripheral. */
  1444. base->SAMR = LPI2C_SAMR_ADDR0(slaveConfig->address0) | LPI2C_SAMR_ADDR1(slaveConfig->address1);
  1445. base->SCFGR1 =
  1446. LPI2C_SCFGR1_ADDRCFG(slaveConfig->addressMatchMode) | LPI2C_SCFGR1_IGNACK(slaveConfig->ignoreAck) |
  1447. LPI2C_SCFGR1_RXCFG(slaveConfig->enableReceivedAddressRead) | LPI2C_SCFGR1_GCEN(slaveConfig->enableGeneralCall) |
  1448. LPI2C_SCFGR1_ACKSTALL(slaveConfig->sclStall.enableAck) | LPI2C_SCFGR1_TXDSTALL(slaveConfig->sclStall.enableTx) |
  1449. LPI2C_SCFGR1_RXSTALL(slaveConfig->sclStall.enableRx) |
  1450. LPI2C_SCFGR1_ADRSTALL(slaveConfig->sclStall.enableAddress);
  1451. /* Calculate SDA filter width. The width is equal to FILTSDA+3 cycles of functional clock.
  1452. And set FILTSDA to 0 disables the fileter, so the min value is 4. */
  1453. tmpReg = LPI2C_SCFGR2_FILTSDA(
  1454. LPI2C_GetCyclesForWidth(sourceClock_Hz, slaveConfig->sdaGlitchFilterWidth_ns, 4U,
  1455. (LPI2C_SCFGR2_FILTSDA_MASK >> LPI2C_SCFGR2_FILTSDA_SHIFT) + 3U, 0U) -
  1456. 3U);
  1457. /* Calculate SDL filter width. The width is equal to FILTSCL+3 cycles of functional clock.
  1458. And set FILTSCL to 0 disables the fileter, so the min value is 4. */
  1459. tmpCycle = LPI2C_GetCyclesForWidth(sourceClock_Hz, slaveConfig->sclGlitchFilterWidth_ns, 4U,
  1460. (LPI2C_SCFGR2_FILTSCL_MASK >> LPI2C_SCFGR2_FILTSCL_SHIFT) + 3U, 0U);
  1461. tmpReg |= LPI2C_SCFGR2_FILTSCL(tmpCycle - 3U);
  1462. /* Calculate data valid time. The time is equal to FILTSCL+DATAVD+3 cycles of functional clock.
  1463. So the min value is FILTSCL+3. */
  1464. tmpReg |= LPI2C_SCFGR2_DATAVD(
  1465. LPI2C_GetCyclesForWidth(sourceClock_Hz, slaveConfig->dataValidDelay_ns, tmpCycle,
  1466. tmpCycle + (LPI2C_SCFGR2_DATAVD_MASK >> LPI2C_SCFGR2_DATAVD_SHIFT), 0U) -
  1467. tmpCycle);
  1468. /* Calculate clock hold time. The time is equal to CLKHOLD+3 cycles of functional clock.
  1469. So the min value is 3. */
  1470. base->SCFGR2 =
  1471. tmpReg | LPI2C_SCFGR2_CLKHOLD(
  1472. LPI2C_GetCyclesForWidth(sourceClock_Hz, slaveConfig->clockHoldTime_ns, 3U,
  1473. (LPI2C_SCFGR2_CLKHOLD_MASK >> LPI2C_SCFGR2_CLKHOLD_SHIFT) + 3U, 0U) -
  1474. 3U);
  1475. /* Save SCR to last so we don't enable slave until it is configured */
  1476. base->SCR = LPI2C_SCR_FILTDZ(!slaveConfig->filterDozeEnable) | LPI2C_SCR_FILTEN(slaveConfig->filterEnable) |
  1477. LPI2C_SCR_SEN(slaveConfig->enableSlave);
  1478. }
  1479. /*!
  1480. * brief Deinitializes the LPI2C slave peripheral.
  1481. *
  1482. * This function disables the LPI2C slave peripheral and gates the clock. It also performs a software
  1483. * reset to restore the peripheral to reset conditions.
  1484. *
  1485. * param base The LPI2C peripheral base address.
  1486. */
  1487. void LPI2C_SlaveDeinit(LPI2C_Type *base)
  1488. {
  1489. LPI2C_SlaveReset(base);
  1490. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  1491. uint32_t instance = LPI2C_GetInstance(base);
  1492. /* Gate the clock. */
  1493. (void)CLOCK_DisableClock(kLpi2cClocks[instance]);
  1494. #if defined(LPI2C_PERIPH_CLOCKS)
  1495. /* Gate the functional clock. */
  1496. CLOCK_DisableClock(kLpi2cPeriphClocks[instance]);
  1497. #endif
  1498. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  1499. }
  1500. /*!
  1501. * @brief Convert provided flags to status code, and clear any errors if present.
  1502. * @param base The LPI2C peripheral base address.
  1503. * @param status Current status flags value that will be checked.
  1504. * @retval #kStatus_Success
  1505. * @retval #kStatus_LPI2C_BitError
  1506. * @retval #kStatus_LPI2C_FifoError
  1507. */
  1508. static status_t LPI2C_SlaveCheckAndClearError(LPI2C_Type *base, uint32_t flags)
  1509. {
  1510. status_t result = kStatus_Success;
  1511. flags &= (uint32_t)kLPI2C_SlaveErrorFlags;
  1512. if (0U != flags)
  1513. {
  1514. if (0U != (flags & (uint32_t)kLPI2C_SlaveBitErrFlag))
  1515. {
  1516. result = kStatus_LPI2C_BitError;
  1517. }
  1518. else if (0U != (flags & (uint32_t)kLPI2C_SlaveFifoErrFlag))
  1519. {
  1520. result = kStatus_LPI2C_FifoError;
  1521. }
  1522. else
  1523. {
  1524. ; /* Intentional empty */
  1525. }
  1526. /* Clear the errors. */
  1527. LPI2C_SlaveClearStatusFlags(base, flags);
  1528. }
  1529. else
  1530. {
  1531. ; /* Intentional empty */
  1532. }
  1533. return result;
  1534. }
  1535. /*!
  1536. * brief Performs a polling send transfer on the I2C bus.
  1537. *
  1538. * param base The LPI2C peripheral base address.
  1539. * param txBuff The pointer to the data to be transferred.
  1540. * param txSize The length in bytes of the data to be transferred.
  1541. * param[out] actualTxSize
  1542. * return Error or success status returned by API.
  1543. */
  1544. status_t LPI2C_SlaveSend(LPI2C_Type *base, void *txBuff, size_t txSize, size_t *actualTxSize)
  1545. {
  1546. status_t result = kStatus_Success;
  1547. uint8_t *buf = (uint8_t *)txBuff;
  1548. size_t remaining = txSize;
  1549. assert(NULL != txBuff);
  1550. #if I2C_RETRY_TIMES != 0U
  1551. uint32_t waitTimes = I2C_RETRY_TIMES;
  1552. #endif
  1553. /* Clear stop flag. */
  1554. LPI2C_SlaveClearStatusFlags(base,
  1555. (uint32_t)kLPI2C_SlaveStopDetectFlag | (uint32_t)kLPI2C_SlaveRepeatedStartDetectFlag);
  1556. while (0U != remaining)
  1557. {
  1558. uint32_t flags;
  1559. /* Wait until we can transmit. */
  1560. do
  1561. {
  1562. /* Check for errors */
  1563. flags = LPI2C_SlaveGetStatusFlags(base);
  1564. result = LPI2C_SlaveCheckAndClearError(base, flags);
  1565. if (kStatus_Success != result)
  1566. {
  1567. if (NULL != actualTxSize)
  1568. {
  1569. *actualTxSize = txSize - remaining;
  1570. }
  1571. break;
  1572. }
  1573. #if I2C_RETRY_TIMES != 0U
  1574. waitTimes--;
  1575. } while ((0U == (flags & ((uint32_t)kLPI2C_SlaveTxReadyFlag | (uint32_t)kLPI2C_SlaveStopDetectFlag |
  1576. (uint32_t)kLPI2C_SlaveRepeatedStartDetectFlag))) &&
  1577. (0U != waitTimes));
  1578. if (0U == waitTimes)
  1579. {
  1580. result = kStatus_LPI2C_Timeout;
  1581. }
  1582. #else
  1583. } while (0U == (flags & ((uint32_t)kLPI2C_SlaveTxReadyFlag | (uint32_t)kLPI2C_SlaveStopDetectFlag |
  1584. (uint32_t)kLPI2C_SlaveRepeatedStartDetectFlag)));
  1585. #endif
  1586. if (kStatus_Success != result)
  1587. {
  1588. break;
  1589. }
  1590. /* Send a byte. */
  1591. if (0U != (flags & (uint32_t)kLPI2C_SlaveTxReadyFlag))
  1592. {
  1593. base->STDR = *buf++;
  1594. --remaining;
  1595. }
  1596. /* Exit loop if we see a stop or restart in transfer*/
  1597. if ((0U != (flags & ((uint32_t)kLPI2C_SlaveStopDetectFlag | (uint32_t)kLPI2C_SlaveRepeatedStartDetectFlag))) &&
  1598. (remaining != 0U))
  1599. {
  1600. LPI2C_SlaveClearStatusFlags(
  1601. base, (uint32_t)kLPI2C_SlaveStopDetectFlag | (uint32_t)kLPI2C_SlaveRepeatedStartDetectFlag);
  1602. break;
  1603. }
  1604. }
  1605. if (NULL != actualTxSize)
  1606. {
  1607. *actualTxSize = txSize - remaining;
  1608. }
  1609. return result;
  1610. }
  1611. /*!
  1612. * brief Performs a polling receive transfer on the I2C bus.
  1613. *
  1614. * param base The LPI2C peripheral base address.
  1615. * param rxBuff The pointer to the data to be transferred.
  1616. * param rxSize The length in bytes of the data to be transferred.
  1617. * param[out] actualRxSize
  1618. * return Error or success status returned by API.
  1619. */
  1620. status_t LPI2C_SlaveReceive(LPI2C_Type *base, void *rxBuff, size_t rxSize, size_t *actualRxSize)
  1621. {
  1622. status_t result = kStatus_Success;
  1623. uint8_t *buf = (uint8_t *)rxBuff;
  1624. size_t remaining = rxSize;
  1625. assert(NULL != rxBuff);
  1626. #if I2C_RETRY_TIMES != 0U
  1627. uint32_t waitTimes = I2C_RETRY_TIMES;
  1628. #endif
  1629. /* Clear stop flag. */
  1630. LPI2C_SlaveClearStatusFlags(base,
  1631. (uint32_t)kLPI2C_SlaveStopDetectFlag | (uint32_t)kLPI2C_SlaveRepeatedStartDetectFlag);
  1632. while (0U != remaining)
  1633. {
  1634. uint32_t flags;
  1635. /* Wait until we can receive. */
  1636. do
  1637. {
  1638. /* Check for errors */
  1639. flags = LPI2C_SlaveGetStatusFlags(base);
  1640. result = LPI2C_SlaveCheckAndClearError(base, flags);
  1641. if (kStatus_Success != result)
  1642. {
  1643. if (NULL != actualRxSize)
  1644. {
  1645. *actualRxSize = rxSize - remaining;
  1646. }
  1647. break;
  1648. }
  1649. #if I2C_RETRY_TIMES != 0U
  1650. waitTimes--;
  1651. } while ((0U == (flags & ((uint32_t)kLPI2C_SlaveRxReadyFlag | (uint32_t)kLPI2C_SlaveStopDetectFlag |
  1652. (uint32_t)kLPI2C_SlaveRepeatedStartDetectFlag))) &&
  1653. (0U != waitTimes));
  1654. if (0U == waitTimes)
  1655. {
  1656. result = kStatus_LPI2C_Timeout;
  1657. }
  1658. #else
  1659. } while (0U == (flags & ((uint32_t)kLPI2C_SlaveRxReadyFlag | (uint32_t)kLPI2C_SlaveStopDetectFlag |
  1660. (uint32_t)kLPI2C_SlaveRepeatedStartDetectFlag)));
  1661. #endif
  1662. if ((status_t)kStatus_Success != result)
  1663. {
  1664. break;
  1665. }
  1666. /* Receive a byte. */
  1667. if (0U != (flags & (uint32_t)kLPI2C_SlaveRxReadyFlag))
  1668. {
  1669. *buf++ = (uint8_t)(base->SRDR & LPI2C_SRDR_DATA_MASK);
  1670. --remaining;
  1671. }
  1672. /* Exit loop if we see a stop or restart */
  1673. if ((0U != (flags & ((uint32_t)kLPI2C_SlaveStopDetectFlag | (uint32_t)kLPI2C_SlaveRepeatedStartDetectFlag))) &&
  1674. (remaining != 0U))
  1675. {
  1676. LPI2C_SlaveClearStatusFlags(
  1677. base, (uint32_t)kLPI2C_SlaveStopDetectFlag | (uint32_t)kLPI2C_SlaveRepeatedStartDetectFlag);
  1678. break;
  1679. }
  1680. }
  1681. if (NULL != actualRxSize)
  1682. {
  1683. *actualRxSize = rxSize - remaining;
  1684. }
  1685. return result;
  1686. }
  1687. /*!
  1688. * brief Creates a new handle for the LPI2C slave non-blocking APIs.
  1689. *
  1690. * The creation of a handle is for use with the non-blocking APIs. Once a handle
  1691. * is created, there is not a corresponding destroy handle. If the user wants to
  1692. * terminate a transfer, the LPI2C_SlaveTransferAbort() API shall be called.
  1693. *
  1694. * note The function also enables the NVIC IRQ for the input LPI2C. Need to notice
  1695. * that on some SoCs the LPI2C IRQ is connected to INTMUX, in this case user needs to
  1696. * enable the associated INTMUX IRQ in application.
  1697. * param base The LPI2C peripheral base address.
  1698. * param[out] handle Pointer to the LPI2C slave driver handle.
  1699. * param callback User provided pointer to the asynchronous callback function.
  1700. * param userData User provided pointer to the application callback data.
  1701. */
  1702. void LPI2C_SlaveTransferCreateHandle(LPI2C_Type *base,
  1703. lpi2c_slave_handle_t *handle,
  1704. lpi2c_slave_transfer_callback_t callback,
  1705. void *userData)
  1706. {
  1707. uint32_t instance;
  1708. assert(NULL != handle);
  1709. /* Clear out the handle. */
  1710. (void)memset(handle, 0, sizeof(*handle));
  1711. /* Look up instance number */
  1712. instance = LPI2C_GetInstance(base);
  1713. /* Save base and instance. */
  1714. handle->callback = callback;
  1715. handle->userData = userData;
  1716. /* Save this handle for IRQ use. */
  1717. s_lpi2cSlaveHandle[instance] = handle;
  1718. /* Set irq handler. */
  1719. s_lpi2cSlaveIsr = LPI2C_SlaveTransferHandleIRQ;
  1720. /* Clear internal IRQ enables and enable NVIC IRQ. */
  1721. LPI2C_SlaveDisableInterrupts(base, (uint32_t)kLPI2C_SlaveIrqFlags);
  1722. (void)EnableIRQ(kLpi2cIrqs[instance]);
  1723. /* Nack by default. */
  1724. base->STAR = LPI2C_STAR_TXNACK_MASK;
  1725. }
  1726. /*!
  1727. * brief Starts accepting slave transfers.
  1728. *
  1729. * Call this API after calling I2C_SlaveInit() and LPI2C_SlaveTransferCreateHandle() to start processing
  1730. * transactions driven by an I2C master. The slave monitors the I2C bus and pass events to the
  1731. * callback that was passed into the call to LPI2C_SlaveTransferCreateHandle(). The callback is always invoked
  1732. * from the interrupt context.
  1733. *
  1734. * The set of events received by the callback is customizable. To do so, set the a eventMask parameter to
  1735. * the OR'd combination of #lpi2c_slave_transfer_event_t enumerators for the events you wish to receive.
  1736. * The #kLPI2C_SlaveTransmitEvent and #kLPI2C_SlaveReceiveEvent events are always enabled and do not need
  1737. * to be included in the mask. Alternatively, you can pass 0 to get a default set of only the transmit and
  1738. * receive events that are always enabled. In addition, the #kLPI2C_SlaveAllEvents constant is provided as
  1739. * a convenient way to enable all events.
  1740. *
  1741. * param base The LPI2C peripheral base address.
  1742. * param handle Pointer to #lpi2c_slave_handle_t structure which stores the transfer state.
  1743. * param eventMask Bit mask formed by OR'ing together #lpi2c_slave_transfer_event_t enumerators to specify
  1744. * which events to send to the callback. Other accepted values are 0 to get a default set of
  1745. * only the transmit and receive events, and #kLPI2C_SlaveAllEvents to enable all events.
  1746. *
  1747. * retval #kStatus_Success Slave transfers were successfully started.
  1748. * retval #kStatus_LPI2C_Busy Slave transfers have already been started on this handle.
  1749. */
  1750. status_t LPI2C_SlaveTransferNonBlocking(LPI2C_Type *base, lpi2c_slave_handle_t *handle, uint32_t eventMask)
  1751. {
  1752. status_t result = kStatus_Success;
  1753. assert(NULL != handle);
  1754. /* Return busy if another transaction is in progress. */
  1755. if (handle->isBusy)
  1756. {
  1757. result = kStatus_LPI2C_Busy;
  1758. }
  1759. else
  1760. {
  1761. /* Return an error if the bus is already in use not by us. */
  1762. uint32_t status = LPI2C_SlaveGetStatusFlags(base);
  1763. if ((0U != (status & (uint32_t)kLPI2C_SlaveBusBusyFlag)) && (0U == (status & (uint32_t)kLPI2C_SlaveBusyFlag)))
  1764. {
  1765. result = kStatus_LPI2C_Busy;
  1766. }
  1767. }
  1768. if ((status_t)kStatus_Success == result)
  1769. {
  1770. /* Disable LPI2C IRQ sources while we configure stuff. */
  1771. LPI2C_SlaveDisableInterrupts(base, (uint32_t)kLPI2C_SlaveIrqFlags);
  1772. /* Clear transfer in handle. */
  1773. (void)memset(&handle->transfer, 0, sizeof(handle->transfer));
  1774. /* Record that we're busy. */
  1775. handle->isBusy = true;
  1776. /* Set up event mask. tx and rx are always enabled. */
  1777. handle->eventMask = eventMask | (uint32_t)kLPI2C_SlaveTransmitEvent | (uint32_t)kLPI2C_SlaveReceiveEvent;
  1778. /* Ack by default. */
  1779. base->STAR = 0U;
  1780. /* Clear all flags. */
  1781. LPI2C_SlaveClearStatusFlags(base, (uint32_t)kLPI2C_SlaveClearFlags);
  1782. /* Enable LPI2C internal IRQ sources. NVIC IRQ was enabled in CreateHandle() */
  1783. LPI2C_SlaveEnableInterrupts(base, (uint32_t)kLPI2C_SlaveIrqFlags);
  1784. }
  1785. return result;
  1786. }
  1787. /*!
  1788. * brief Gets the slave transfer status during a non-blocking transfer.
  1789. * param base The LPI2C peripheral base address.
  1790. * param handle Pointer to i2c_slave_handle_t structure.
  1791. * param[out] count Pointer to a value to hold the number of bytes transferred. May be NULL if the count is not
  1792. * required.
  1793. * retval #kStatus_Success
  1794. * retval #kStatus_NoTransferInProgress
  1795. */
  1796. status_t LPI2C_SlaveTransferGetCount(LPI2C_Type *base, lpi2c_slave_handle_t *handle, size_t *count)
  1797. {
  1798. status_t status = kStatus_Success;
  1799. assert(NULL != handle);
  1800. if (count == NULL)
  1801. {
  1802. status = kStatus_InvalidArgument;
  1803. }
  1804. /* Catch when there is not an active transfer. */
  1805. else if (!handle->isBusy)
  1806. {
  1807. *count = 0;
  1808. status = kStatus_NoTransferInProgress;
  1809. }
  1810. /* For an active transfer, just return the count from the handle. */
  1811. else
  1812. {
  1813. *count = handle->transferredCount;
  1814. }
  1815. return status;
  1816. }
  1817. /*!
  1818. * brief Aborts the slave non-blocking transfers.
  1819. * note This API could be called at any time to stop slave for handling the bus events.
  1820. * param base The LPI2C peripheral base address.
  1821. * param handle Pointer to #lpi2c_slave_handle_t structure which stores the transfer state.
  1822. * retval #kStatus_Success
  1823. * retval #kStatus_LPI2C_Idle
  1824. */
  1825. void LPI2C_SlaveTransferAbort(LPI2C_Type *base, lpi2c_slave_handle_t *handle)
  1826. {
  1827. assert(NULL != handle);
  1828. /* Return idle if no transaction is in progress. */
  1829. if (handle->isBusy)
  1830. {
  1831. /* Disable LPI2C IRQ sources. */
  1832. LPI2C_SlaveDisableInterrupts(base, (uint32_t)kLPI2C_SlaveIrqFlags);
  1833. /* Nack by default. */
  1834. base->STAR = LPI2C_STAR_TXNACK_MASK;
  1835. /* Reset transfer info. */
  1836. (void)memset(&handle->transfer, 0, sizeof(handle->transfer));
  1837. /* We're no longer busy. */
  1838. handle->isBusy = false;
  1839. }
  1840. }
  1841. /*!
  1842. * brief Reusable routine to handle slave interrupts.
  1843. * note This function does not need to be called unless you are reimplementing the
  1844. * non blocking API's interrupt handler routines to add special functionality.
  1845. * param base The LPI2C peripheral base address.
  1846. * param handle Pointer to #lpi2c_slave_handle_t structure which stores the transfer state.
  1847. */
  1848. void LPI2C_SlaveTransferHandleIRQ(LPI2C_Type *base, lpi2c_slave_handle_t *handle)
  1849. {
  1850. uint32_t flags;
  1851. lpi2c_slave_transfer_t *xfer;
  1852. /* Check for a valid handle in case of a spurious interrupt. */
  1853. if (NULL != handle)
  1854. {
  1855. xfer = &handle->transfer;
  1856. /* Get status flags. */
  1857. flags = LPI2C_SlaveGetStatusFlags(base);
  1858. if (0U != (flags & ((uint32_t)kLPI2C_SlaveBitErrFlag | (uint32_t)kLPI2C_SlaveFifoErrFlag)))
  1859. {
  1860. xfer->event = kLPI2C_SlaveCompletionEvent;
  1861. xfer->completionStatus = LPI2C_SlaveCheckAndClearError(base, flags);
  1862. if ((0U != (handle->eventMask & (uint32_t)kLPI2C_SlaveCompletionEvent)) && (NULL != handle->callback))
  1863. {
  1864. handle->callback(base, xfer, handle->userData);
  1865. }
  1866. }
  1867. else
  1868. {
  1869. if (0U !=
  1870. (flags & (((uint32_t)kLPI2C_SlaveRepeatedStartDetectFlag) | ((uint32_t)kLPI2C_SlaveStopDetectFlag))))
  1871. {
  1872. xfer->event = (0U != (flags & (uint32_t)kLPI2C_SlaveRepeatedStartDetectFlag)) ?
  1873. kLPI2C_SlaveRepeatedStartEvent :
  1874. kLPI2C_SlaveCompletionEvent;
  1875. xfer->receivedAddress = 0U;
  1876. xfer->completionStatus = kStatus_Success;
  1877. xfer->transferredCount = handle->transferredCount;
  1878. if (xfer->event == kLPI2C_SlaveCompletionEvent)
  1879. {
  1880. handle->isBusy = false;
  1881. }
  1882. if (handle->wasTransmit)
  1883. {
  1884. /* Subtract one from the transmit count to offset the fact that LPI2C asserts the */
  1885. /* tx flag before it sees the nack from the master-receiver, thus causing one more */
  1886. /* count that the master actually receives. */
  1887. --xfer->transferredCount;
  1888. handle->wasTransmit = false;
  1889. }
  1890. /* Clear the flag. */
  1891. LPI2C_SlaveClearStatusFlags(base, flags & ((uint32_t)kLPI2C_SlaveRepeatedStartDetectFlag |
  1892. (uint32_t)kLPI2C_SlaveStopDetectFlag));
  1893. /* Revert to sending an Ack by default, in case we sent a Nack for receive. */
  1894. base->STAR = 0U;
  1895. if ((0U != (handle->eventMask & (uint32_t)xfer->event)) && (NULL != handle->callback))
  1896. {
  1897. handle->callback(base, xfer, handle->userData);
  1898. }
  1899. if (0U != (flags & (uint32_t)kLPI2C_SlaveStopDetectFlag))
  1900. {
  1901. /* Clean up transfer info on completion, after the callback has been invoked. */
  1902. (void)memset(&handle->transfer, 0, sizeof(handle->transfer));
  1903. }
  1904. }
  1905. if (0U != (flags & (uint32_t)kLPI2C_SlaveAddressValidFlag))
  1906. {
  1907. xfer->event = kLPI2C_SlaveAddressMatchEvent;
  1908. xfer->receivedAddress = (uint8_t)(base->SASR & LPI2C_SASR_RADDR_MASK);
  1909. /* Update handle status to busy because slave is addressed. */
  1910. handle->isBusy = true;
  1911. if ((0U != (handle->eventMask & (uint32_t)kLPI2C_SlaveAddressMatchEvent)) && (NULL != handle->callback))
  1912. {
  1913. handle->callback(base, xfer, handle->userData);
  1914. }
  1915. }
  1916. if (0U != (flags & (uint32_t)kLPI2C_SlaveTransmitAckFlag))
  1917. {
  1918. xfer->event = kLPI2C_SlaveTransmitAckEvent;
  1919. if ((0U != (handle->eventMask & (uint32_t)kLPI2C_SlaveTransmitAckEvent)) && (NULL != handle->callback))
  1920. {
  1921. handle->callback(base, xfer, handle->userData);
  1922. }
  1923. }
  1924. /* Handle transmit and receive. */
  1925. if (0U != (flags & (uint32_t)kLPI2C_SlaveTxReadyFlag))
  1926. {
  1927. handle->wasTransmit = true;
  1928. /* If we're out of data, invoke callback to get more. */
  1929. if ((NULL == xfer->data) || (0U == xfer->dataSize))
  1930. {
  1931. xfer->event = kLPI2C_SlaveTransmitEvent;
  1932. if (NULL != handle->callback)
  1933. {
  1934. handle->callback(base, xfer, handle->userData);
  1935. }
  1936. /* Clear the transferred count now that we have a new buffer. */
  1937. handle->transferredCount = 0U;
  1938. }
  1939. /* Transmit a byte. */
  1940. if ((NULL != xfer->data) && (0U != xfer->dataSize))
  1941. {
  1942. base->STDR = *xfer->data++;
  1943. --xfer->dataSize;
  1944. ++handle->transferredCount;
  1945. }
  1946. }
  1947. if (0U != (flags & (uint32_t)kLPI2C_SlaveRxReadyFlag))
  1948. {
  1949. /* If we're out of room in the buffer, invoke callback to get another. */
  1950. if ((NULL == xfer->data) || (0U == xfer->dataSize))
  1951. {
  1952. xfer->event = kLPI2C_SlaveReceiveEvent;
  1953. if (NULL != handle->callback)
  1954. {
  1955. handle->callback(base, xfer, handle->userData);
  1956. }
  1957. /* Clear the transferred count now that we have a new buffer. */
  1958. handle->transferredCount = 0U;
  1959. }
  1960. /* Receive a byte. */
  1961. if ((NULL != xfer->data) && (0U != xfer->dataSize))
  1962. {
  1963. *xfer->data++ = (uint8_t)base->SRDR;
  1964. --xfer->dataSize;
  1965. ++handle->transferredCount;
  1966. }
  1967. else
  1968. {
  1969. /* We don't have any room to receive more data, so send a nack. */
  1970. base->STAR = LPI2C_STAR_TXNACK_MASK;
  1971. }
  1972. }
  1973. }
  1974. }
  1975. }
  1976. #if !(defined(FSL_FEATURE_I2C_HAS_NO_IRQ) && FSL_FEATURE_I2C_HAS_NO_IRQ)
  1977. /*!
  1978. * @brief Shared IRQ handler that can call both master and slave ISRs.
  1979. *
  1980. * The master and slave ISRs are called through function pointers in order to decouple
  1981. * this code from the ISR functions. Without this, the linker would always pull in both
  1982. * ISRs and every function they call, even if only the functional API was used.
  1983. *
  1984. * @param base The LPI2C peripheral base address.
  1985. * @param instance The LPI2C peripheral instance number.
  1986. */
  1987. static void LPI2C_CommonIRQHandler(LPI2C_Type *base, uint32_t instance)
  1988. {
  1989. /* Check for master IRQ. */
  1990. if ((0U != (base->MCR & LPI2C_MCR_MEN_MASK)) && (NULL != s_lpi2cMasterIsr))
  1991. {
  1992. /* Master mode. */
  1993. s_lpi2cMasterIsr(base, s_lpi2cMasterHandle[instance]);
  1994. }
  1995. /* Check for slave IRQ. */
  1996. if ((0U != (base->SCR & LPI2C_SCR_SEN_MASK)) && (NULL != s_lpi2cSlaveIsr))
  1997. {
  1998. /* Slave mode. */
  1999. s_lpi2cSlaveIsr(base, s_lpi2cSlaveHandle[instance]);
  2000. }
  2001. SDK_ISR_EXIT_BARRIER;
  2002. }
  2003. #endif
  2004. #if defined(LPI2C0)
  2005. /* Implementation of LPI2C0 handler named in startup code. */
  2006. void LPI2C0_DriverIRQHandler(void);
  2007. void LPI2C0_DriverIRQHandler(void)
  2008. {
  2009. LPI2C_CommonIRQHandler(LPI2C0, 0U);
  2010. }
  2011. #endif
  2012. #if defined(LPI2C1)
  2013. /* Implementation of LPI2C1 handler named in startup code. */
  2014. void LPI2C1_DriverIRQHandler(void);
  2015. void LPI2C1_DriverIRQHandler(void)
  2016. {
  2017. LPI2C_CommonIRQHandler(LPI2C1, 1U);
  2018. }
  2019. #endif
  2020. #if defined(LPI2C2)
  2021. /* Implementation of LPI2C2 handler named in startup code. */
  2022. void LPI2C2_DriverIRQHandler(void);
  2023. void LPI2C2_DriverIRQHandler(void)
  2024. {
  2025. LPI2C_CommonIRQHandler(LPI2C2, 2U);
  2026. }
  2027. #endif
  2028. #if defined(LPI2C3)
  2029. /* Implementation of LPI2C3 handler named in startup code. */
  2030. void LPI2C3_DriverIRQHandler(void);
  2031. void LPI2C3_DriverIRQHandler(void)
  2032. {
  2033. LPI2C_CommonIRQHandler(LPI2C3, 3U);
  2034. }
  2035. #endif
  2036. #if defined(LPI2C4)
  2037. /* Implementation of LPI2C4 handler named in startup code. */
  2038. void LPI2C4_DriverIRQHandler(void);
  2039. void LPI2C4_DriverIRQHandler(void)
  2040. {
  2041. LPI2C_CommonIRQHandler(LPI2C4, 4U);
  2042. }
  2043. #endif
  2044. #if defined(LPI2C5)
  2045. /* Implementation of LPI2C5 handler named in startup code. */
  2046. void LPI2C5_DriverIRQHandler(void);
  2047. void LPI2C5_DriverIRQHandler(void)
  2048. {
  2049. LPI2C_CommonIRQHandler(LPI2C5, 5U);
  2050. }
  2051. #endif
  2052. #if defined(LPI2C6)
  2053. /* Implementation of LPI2C6 handler named in startup code. */
  2054. void LPI2C6_DriverIRQHandler(void);
  2055. void LPI2C6_DriverIRQHandler(void)
  2056. {
  2057. LPI2C_CommonIRQHandler(LPI2C6, 6U);
  2058. }
  2059. #endif
  2060. #if defined(CM4_0__LPI2C)
  2061. /* Implementation of CM4_0__LPI2C handler named in startup code. */
  2062. void M4_0_LPI2C_DriverIRQHandler(void);
  2063. void M4_0_LPI2C_DriverIRQHandler(void)
  2064. {
  2065. LPI2C_CommonIRQHandler(CM4_0__LPI2C, LPI2C_GetInstance(CM4_0__LPI2C));
  2066. }
  2067. #endif
  2068. #if defined(CM4__LPI2C)
  2069. /* Implementation of CM4__LPI2C handler named in startup code. */
  2070. void M4_LPI2C_DriverIRQHandler(void);
  2071. void M4_LPI2C_DriverIRQHandler(void)
  2072. {
  2073. LPI2C_CommonIRQHandler(CM4__LPI2C, LPI2C_GetInstance(CM4__LPI2C));
  2074. }
  2075. #endif
  2076. #if defined(CM4_1__LPI2C)
  2077. /* Implementation of CM4_1__LPI2C handler named in startup code. */
  2078. void M4_1_LPI2C_DriverIRQHandler(void);
  2079. void M4_1_LPI2C_DriverIRQHandler(void)
  2080. {
  2081. LPI2C_CommonIRQHandler(CM4_1__LPI2C, LPI2C_GetInstance(CM4_1__LPI2C));
  2082. }
  2083. #endif
  2084. #if defined(DMA__LPI2C0)
  2085. /* Implementation of DMA__LPI2C0 handler named in startup code. */
  2086. void DMA_I2C0_INT_DriverIRQHandler(void);
  2087. void DMA_I2C0_INT_DriverIRQHandler(void)
  2088. {
  2089. LPI2C_CommonIRQHandler(DMA__LPI2C0, LPI2C_GetInstance(DMA__LPI2C0));
  2090. }
  2091. #endif
  2092. #if defined(DMA__LPI2C1)
  2093. /* Implementation of DMA__LPI2C1 handler named in startup code. */
  2094. void DMA_I2C1_INT_DriverIRQHandler(void);
  2095. void DMA_I2C1_INT_DriverIRQHandler(void)
  2096. {
  2097. LPI2C_CommonIRQHandler(DMA__LPI2C1, LPI2C_GetInstance(DMA__LPI2C1));
  2098. }
  2099. #endif
  2100. #if defined(DMA__LPI2C2)
  2101. /* Implementation of DMA__LPI2C2 handler named in startup code. */
  2102. void DMA_I2C2_INT_DriverIRQHandler(void);
  2103. void DMA_I2C2_INT_DriverIRQHandler(void)
  2104. {
  2105. LPI2C_CommonIRQHandler(DMA__LPI2C2, LPI2C_GetInstance(DMA__LPI2C2));
  2106. }
  2107. #endif
  2108. #if defined(DMA__LPI2C3)
  2109. /* Implementation of DMA__LPI2C3 handler named in startup code. */
  2110. void DMA_I2C3_INT_DriverIRQHandler(void);
  2111. void DMA_I2C3_INT_DriverIRQHandler(void)
  2112. {
  2113. LPI2C_CommonIRQHandler(DMA__LPI2C3, LPI2C_GetInstance(DMA__LPI2C3));
  2114. }
  2115. #endif
  2116. #if defined(DMA__LPI2C4)
  2117. /* Implementation of DMA__LPI2C3 handler named in startup code. */
  2118. void DMA_I2C4_INT_DriverIRQHandler(void);
  2119. void DMA_I2C4_INT_DriverIRQHandler(void)
  2120. {
  2121. LPI2C_CommonIRQHandler(DMA__LPI2C4, LPI2C_GetInstance(DMA__LPI2C4));
  2122. }
  2123. #endif
  2124. #if defined(ADMA__LPI2C0)
  2125. /* Implementation of DMA__LPI2C0 handler named in startup code. */
  2126. void ADMA_I2C0_INT_DriverIRQHandler(void);
  2127. void ADMA_I2C0_INT_DriverIRQHandler(void)
  2128. {
  2129. LPI2C_CommonIRQHandler(ADMA__LPI2C0, LPI2C_GetInstance(ADMA__LPI2C0));
  2130. }
  2131. #endif
  2132. #if defined(ADMA__LPI2C1)
  2133. /* Implementation of DMA__LPI2C1 handler named in startup code. */
  2134. void ADMA_I2C1_INT_DriverIRQHandler(void);
  2135. void ADMA_I2C1_INT_DriverIRQHandler(void)
  2136. {
  2137. LPI2C_CommonIRQHandler(ADMA__LPI2C1, LPI2C_GetInstance(ADMA__LPI2C1));
  2138. }
  2139. #endif
  2140. #if defined(ADMA__LPI2C2)
  2141. /* Implementation of DMA__LPI2C2 handler named in startup code. */
  2142. void ADMA_I2C2_INT_DriverIRQHandler(void);
  2143. void ADMA_I2C2_INT_DriverIRQHandler(void)
  2144. {
  2145. LPI2C_CommonIRQHandler(ADMA__LPI2C2, LPI2C_GetInstance(ADMA__LPI2C2));
  2146. }
  2147. #endif
  2148. #if defined(ADMA__LPI2C3)
  2149. /* Implementation of DMA__LPI2C3 handler named in startup code. */
  2150. void ADMA_I2C3_INT_DriverIRQHandler(void);
  2151. void ADMA_I2C3_INT_DriverIRQHandler(void)
  2152. {
  2153. LPI2C_CommonIRQHandler(ADMA__LPI2C3, LPI2C_GetInstance(ADMA__LPI2C3));
  2154. }
  2155. #endif
  2156. #if defined(ADMA__LPI2C4)
  2157. /* Implementation of DMA__LPI2C3 handler named in startup code. */
  2158. void ADMA_I2C4_INT_DriverIRQHandler(void);
  2159. void ADMA_I2C4_INT_DriverIRQHandler(void)
  2160. {
  2161. LPI2C_CommonIRQHandler(ADMA__LPI2C4, LPI2C_GetInstance(ADMA__LPI2C4));
  2162. }
  2163. #endif