fsl_lpi2c.c 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861
  1. /*
  2. * Copyright (c) 2015, Freescale Semiconductor, Inc.
  3. * Copyright 2016-2017 NXP
  4. *
  5. * Redistribution and use in source and binary forms, with or without modification,
  6. * are permitted provided that the following conditions are met:
  7. *
  8. * o Redistributions of source code must retain the above copyright notice, this list
  9. * of conditions and the following disclaimer.
  10. *
  11. * o Redistributions in binary form must reproduce the above copyright notice, this
  12. * list of conditions and the following disclaimer in the documentation and/or
  13. * other materials provided with the distribution.
  14. *
  15. * o Neither the name of the copyright holder nor the names of its
  16. * contributors may be used to endorse or promote products derived from this
  17. * software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  20. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  21. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  23. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  24. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  25. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  26. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  28. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #include "fsl_lpi2c.h"
  31. #include <stdlib.h>
  32. #include <string.h>
  33. /*******************************************************************************
  34. * Definitions
  35. ******************************************************************************/
  36. /*! @brief Common sets of flags used by the driver. */
  37. enum _lpi2c_flag_constants
  38. {
  39. /*! All flags which are cleared by the driver upon starting a transfer. */
  40. kMasterClearFlags = kLPI2C_MasterEndOfPacketFlag | kLPI2C_MasterStopDetectFlag | kLPI2C_MasterNackDetectFlag |
  41. kLPI2C_MasterArbitrationLostFlag | kLPI2C_MasterFifoErrFlag | kLPI2C_MasterPinLowTimeoutFlag |
  42. kLPI2C_MasterDataMatchFlag,
  43. /*! IRQ sources enabled by the non-blocking transactional API. */
  44. kMasterIrqFlags = kLPI2C_MasterArbitrationLostFlag | kLPI2C_MasterTxReadyFlag | kLPI2C_MasterRxReadyFlag |
  45. kLPI2C_MasterStopDetectFlag | kLPI2C_MasterNackDetectFlag | kLPI2C_MasterPinLowTimeoutFlag |
  46. kLPI2C_MasterFifoErrFlag,
  47. /*! Errors to check for. */
  48. kMasterErrorFlags = kLPI2C_MasterNackDetectFlag | kLPI2C_MasterArbitrationLostFlag | kLPI2C_MasterFifoErrFlag |
  49. kLPI2C_MasterPinLowTimeoutFlag,
  50. /*! All flags which are cleared by the driver upon starting a transfer. */
  51. kSlaveClearFlags = kLPI2C_SlaveRepeatedStartDetectFlag | kLPI2C_SlaveStopDetectFlag | kLPI2C_SlaveBitErrFlag |
  52. kLPI2C_SlaveFifoErrFlag,
  53. /*! IRQ sources enabled by the non-blocking transactional API. */
  54. kSlaveIrqFlags = kLPI2C_SlaveTxReadyFlag | kLPI2C_SlaveRxReadyFlag | kLPI2C_SlaveStopDetectFlag |
  55. kLPI2C_SlaveRepeatedStartDetectFlag | kLPI2C_SlaveFifoErrFlag | kLPI2C_SlaveBitErrFlag |
  56. kLPI2C_SlaveTransmitAckFlag | kLPI2C_SlaveAddressValidFlag,
  57. /*! Errors to check for. */
  58. kSlaveErrorFlags = kLPI2C_SlaveFifoErrFlag | kLPI2C_SlaveBitErrFlag,
  59. };
  60. /* ! @brief LPI2C master fifo commands. */
  61. enum _lpi2c_master_fifo_cmd
  62. {
  63. kTxDataCmd = LPI2C_MTDR_CMD(0x0U), /*!< Transmit DATA[7:0] */
  64. kRxDataCmd = LPI2C_MTDR_CMD(0X1U), /*!< Receive (DATA[7:0] + 1) bytes */
  65. kStopCmd = LPI2C_MTDR_CMD(0x2U), /*!< Generate STOP condition */
  66. kStartCmd = LPI2C_MTDR_CMD(0x4U), /*!< Generate(repeated) START and transmit address in DATA[[7:0] */
  67. };
  68. /*!
  69. * @brief Default watermark values.
  70. *
  71. * The default watermarks are set to zero.
  72. */
  73. enum _lpi2c_default_watermarks
  74. {
  75. kDefaultTxWatermark = 0,
  76. kDefaultRxWatermark = 0,
  77. };
  78. /*! @brief States for the state machine used by transactional APIs. */
  79. enum _lpi2c_transfer_states
  80. {
  81. kIdleState = 0,
  82. kSendCommandState,
  83. kIssueReadCommandState,
  84. kTransferDataState,
  85. kStopState,
  86. kWaitForCompletionState,
  87. };
  88. /*! @brief Typedef for master interrupt handler. */
  89. typedef void (*lpi2c_master_isr_t)(LPI2C_Type *base, lpi2c_master_handle_t *handle);
  90. /*! @brief Typedef for slave interrupt handler. */
  91. typedef void (*lpi2c_slave_isr_t)(LPI2C_Type *base, lpi2c_slave_handle_t *handle);
  92. /*******************************************************************************
  93. * Prototypes
  94. ******************************************************************************/
  95. /* Not static so it can be used from fsl_lpi2c_edma.c. */
  96. uint32_t LPI2C_GetInstance(LPI2C_Type *base);
  97. static uint32_t LPI2C_GetCyclesForWidth(uint32_t sourceClock_Hz,
  98. uint32_t width_ns,
  99. uint32_t maxCycles,
  100. uint32_t prescaler);
  101. /* Not static so it can be used from fsl_lpi2c_edma.c. */
  102. status_t LPI2C_MasterCheckAndClearError(LPI2C_Type *base, uint32_t status);
  103. static status_t LPI2C_MasterWaitForTxReady(LPI2C_Type *base);
  104. /* Not static so it can be used from fsl_lpi2c_edma.c. */
  105. status_t LPI2C_CheckForBusyBus(LPI2C_Type *base);
  106. static status_t LPI2C_RunTransferStateMachine(LPI2C_Type *base, lpi2c_master_handle_t *handle, bool *isDone);
  107. static void LPI2C_InitTransferStateMachine(lpi2c_master_handle_t *handle);
  108. static status_t LPI2C_SlaveCheckAndClearError(LPI2C_Type *base, uint32_t flags);
  109. static void LPI2C_CommonIRQHandler(LPI2C_Type *base, uint32_t instance);
  110. /*******************************************************************************
  111. * Variables
  112. ******************************************************************************/
  113. /*! @brief Array to map LPI2C instance number to base pointer. */
  114. static LPI2C_Type *const kLpi2cBases[] = LPI2C_BASE_PTRS;
  115. /*! @brief Array to map LPI2C instance number to IRQ number. */
  116. static IRQn_Type const kLpi2cIrqs[] = LPI2C_IRQS;
  117. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  118. /*! @brief Array to map LPI2C instance number to clock gate enum. */
  119. static clock_ip_name_t const kLpi2cClocks[] = LPI2C_CLOCKS;
  120. #if defined(LPI2C_PERIPH_CLOCKS)
  121. /*! @brief Array to map LPI2C instance number to pheripheral clock gate enum. */
  122. static const clock_ip_name_t kLpi2cPeriphClocks[] = LPI2C_PERIPH_CLOCKS;
  123. #endif
  124. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  125. /*! @brief Pointer to master IRQ handler for each instance. */
  126. static lpi2c_master_isr_t s_lpi2cMasterIsr;
  127. /*! @brief Pointers to master handles for each instance. */
  128. static lpi2c_master_handle_t *s_lpi2cMasterHandle[FSL_FEATURE_SOC_LPI2C_COUNT];
  129. /*! @brief Pointer to slave IRQ handler for each instance. */
  130. static lpi2c_slave_isr_t s_lpi2cSlaveIsr;
  131. /*! @brief Pointers to slave handles for each instance. */
  132. static lpi2c_slave_handle_t *s_lpi2cSlaveHandle[FSL_FEATURE_SOC_LPI2C_COUNT];
  133. /*******************************************************************************
  134. * Code
  135. ******************************************************************************/
  136. /*!
  137. * @brief Returns an instance number given a base address.
  138. *
  139. * If an invalid base address is passed, debug builds will assert. Release builds will just return
  140. * instance number 0.
  141. *
  142. * @param base The LPI2C peripheral base address.
  143. * @return LPI2C instance number starting from 0.
  144. */
  145. uint32_t LPI2C_GetInstance(LPI2C_Type *base)
  146. {
  147. uint32_t instance;
  148. for (instance = 0; instance < ARRAY_SIZE(kLpi2cBases); ++instance)
  149. {
  150. if (kLpi2cBases[instance] == base)
  151. {
  152. return instance;
  153. }
  154. }
  155. assert(false);
  156. return 0;
  157. }
  158. /*!
  159. * @brief Computes a cycle count for a given time in nanoseconds.
  160. * @param sourceClock_Hz LPI2C functional clock frequency in Hertz.
  161. * @param width_ns Desired with in nanoseconds.
  162. * @param maxCycles Maximum cycle count, determined by the number of bits wide the cycle count field is.
  163. * @param prescaler LPI2C prescaler setting. Pass 1 if the prescaler should not be used, as for slave glitch widths.
  164. */
  165. static uint32_t LPI2C_GetCyclesForWidth(uint32_t sourceClock_Hz,
  166. uint32_t width_ns,
  167. uint32_t maxCycles,
  168. uint32_t prescaler)
  169. {
  170. uint32_t busCycle_ns = 1000000 / (sourceClock_Hz / prescaler / 1000);
  171. uint32_t cycles = 0;
  172. /* Search for the cycle count just below the desired glitch width. */
  173. while ((((cycles + 1) * busCycle_ns) < width_ns) && (cycles + 1 < maxCycles))
  174. {
  175. ++cycles;
  176. }
  177. /* If we end up with zero cycles, then set the filter to a single cycle unless the */
  178. /* bus clock is greater than 10x the desired glitch width. */
  179. if ((cycles == 0) && (busCycle_ns <= (width_ns * 10)))
  180. {
  181. cycles = 1;
  182. }
  183. return cycles;
  184. }
  185. /*!
  186. * @brief Convert provided flags to status code, and clear any errors if present.
  187. * @param base The LPI2C peripheral base address.
  188. * @param status Current status flags value that will be checked.
  189. * @retval #kStatus_Success
  190. * @retval #kStatus_LPI2C_PinLowTimeout
  191. * @retval #kStatus_LPI2C_ArbitrationLost
  192. * @retval #kStatus_LPI2C_Nak
  193. * @retval #kStatus_LPI2C_FifoError
  194. */
  195. status_t LPI2C_MasterCheckAndClearError(LPI2C_Type *base, uint32_t status)
  196. {
  197. status_t result = kStatus_Success;
  198. /* Check for error. These errors cause a stop to automatically be sent. We must */
  199. /* clear the errors before a new transfer can start. */
  200. status &= kMasterErrorFlags;
  201. if (status)
  202. {
  203. /* Select the correct error code. Ordered by severity, with bus issues first. */
  204. if (status & kLPI2C_MasterPinLowTimeoutFlag)
  205. {
  206. result = kStatus_LPI2C_PinLowTimeout;
  207. }
  208. else if (status & kLPI2C_MasterArbitrationLostFlag)
  209. {
  210. result = kStatus_LPI2C_ArbitrationLost;
  211. }
  212. else if (status & kLPI2C_MasterNackDetectFlag)
  213. {
  214. result = kStatus_LPI2C_Nak;
  215. }
  216. else if (status & kLPI2C_MasterFifoErrFlag)
  217. {
  218. result = kStatus_LPI2C_FifoError;
  219. }
  220. else
  221. {
  222. assert(false);
  223. }
  224. /* Clear the flags. */
  225. LPI2C_MasterClearStatusFlags(base, status);
  226. /* Reset fifos. These flags clear automatically. */
  227. base->MCR |= LPI2C_MCR_RRF_MASK | LPI2C_MCR_RTF_MASK;
  228. }
  229. return result;
  230. }
  231. /*!
  232. * @brief Wait until there is room in the tx fifo.
  233. * @param base The LPI2C peripheral base address.
  234. * @retval #kStatus_Success
  235. * @retval #kStatus_LPI2C_PinLowTimeout
  236. * @retval #kStatus_LPI2C_ArbitrationLost
  237. * @retval #kStatus_LPI2C_Nak
  238. * @retval #kStatus_LPI2C_FifoError
  239. */
  240. static status_t LPI2C_MasterWaitForTxReady(LPI2C_Type *base)
  241. {
  242. uint32_t status;
  243. size_t txCount;
  244. size_t txFifoSize = FSL_FEATURE_LPI2C_FIFO_SIZEn(base);
  245. #if LPI2C_WAIT_TIMEOUT
  246. uint32_t waitTimes = LPI2C_WAIT_TIMEOUT;
  247. #endif
  248. do
  249. {
  250. status_t result;
  251. /* Get the number of words in the tx fifo and compute empty slots. */
  252. LPI2C_MasterGetFifoCounts(base, NULL, &txCount);
  253. txCount = txFifoSize - txCount;
  254. /* Check for error flags. */
  255. status = LPI2C_MasterGetStatusFlags(base);
  256. result = LPI2C_MasterCheckAndClearError(base, status);
  257. if (result)
  258. {
  259. return result;
  260. }
  261. #if LPI2C_WAIT_TIMEOUT
  262. } while ((!txCount) && (--waitTimes));
  263. if (waitTimes == 0)
  264. {
  265. return kStatus_LPI2C_Timeout;
  266. }
  267. #else
  268. } while (!txCount);
  269. #endif
  270. return kStatus_Success;
  271. }
  272. /*!
  273. * @brief Make sure the bus isn't already busy.
  274. *
  275. * A busy bus is allowed if we are the one driving it.
  276. *
  277. * @param base The LPI2C peripheral base address.
  278. * @retval #kStatus_Success
  279. * @retval #kStatus_LPI2C_Busy
  280. */
  281. status_t LPI2C_CheckForBusyBus(LPI2C_Type *base)
  282. {
  283. uint32_t status = LPI2C_MasterGetStatusFlags(base);
  284. if ((status & kLPI2C_MasterBusBusyFlag) && (!(status & kLPI2C_MasterBusyFlag)))
  285. {
  286. return kStatus_LPI2C_Busy;
  287. }
  288. return kStatus_Success;
  289. }
  290. void LPI2C_MasterGetDefaultConfig(lpi2c_master_config_t *masterConfig)
  291. {
  292. masterConfig->enableMaster = true;
  293. masterConfig->debugEnable = false;
  294. masterConfig->enableDoze = true;
  295. masterConfig->ignoreAck = false;
  296. masterConfig->pinConfig = kLPI2C_2PinOpenDrain;
  297. masterConfig->baudRate_Hz = 100000U;
  298. masterConfig->busIdleTimeout_ns = 0;
  299. masterConfig->pinLowTimeout_ns = 0;
  300. masterConfig->sdaGlitchFilterWidth_ns = 0;
  301. masterConfig->sclGlitchFilterWidth_ns = 0;
  302. masterConfig->hostRequest.enable = false;
  303. masterConfig->hostRequest.source = kLPI2C_HostRequestExternalPin;
  304. masterConfig->hostRequest.polarity = kLPI2C_HostRequestPinActiveHigh;
  305. }
  306. void LPI2C_MasterInit(LPI2C_Type *base, const lpi2c_master_config_t *masterConfig, uint32_t sourceClock_Hz)
  307. {
  308. uint32_t prescaler;
  309. uint32_t cycles;
  310. uint32_t cfgr2;
  311. uint32_t value;
  312. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  313. uint32_t instance = LPI2C_GetInstance(base);
  314. /* Ungate the clock. */
  315. CLOCK_EnableClock(kLpi2cClocks[instance]);
  316. #if defined(LPI2C_PERIPH_CLOCKS)
  317. /* Ungate the functional clock in initialize function. */
  318. CLOCK_EnableClock(kLpi2cPeriphClocks[instance]);
  319. #endif
  320. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  321. /* Reset peripheral before configuring it. */
  322. LPI2C_MasterReset(base);
  323. /* Doze bit: 0 is enable, 1 is disable */
  324. base->MCR = LPI2C_MCR_DBGEN(masterConfig->debugEnable) | LPI2C_MCR_DOZEN(!(masterConfig->enableDoze));
  325. /* host request */
  326. value = base->MCFGR0;
  327. value &= (~(LPI2C_MCFGR0_HREN_MASK | LPI2C_MCFGR0_HRPOL_MASK | LPI2C_MCFGR0_HRSEL_MASK));
  328. value |= LPI2C_MCFGR0_HREN(masterConfig->hostRequest.enable) |
  329. LPI2C_MCFGR0_HRPOL(masterConfig->hostRequest.polarity) |
  330. LPI2C_MCFGR0_HRSEL(masterConfig->hostRequest.source);
  331. base->MCFGR0 = value;
  332. /* pin config and ignore ack */
  333. value = base->MCFGR1;
  334. value &= ~(LPI2C_MCFGR1_PINCFG_MASK | LPI2C_MCFGR1_IGNACK_MASK);
  335. value |= LPI2C_MCFGR1_PINCFG(masterConfig->pinConfig);
  336. value |= LPI2C_MCFGR1_IGNACK(masterConfig->ignoreAck);
  337. base->MCFGR1 = value;
  338. LPI2C_MasterSetWatermarks(base, kDefaultTxWatermark, kDefaultRxWatermark);
  339. LPI2C_MasterSetBaudRate(base, sourceClock_Hz, masterConfig->baudRate_Hz);
  340. /* Configure glitch filters and bus idle and pin low timeouts. */
  341. prescaler = (base->MCFGR1 & LPI2C_MCFGR1_PRESCALE_MASK) >> LPI2C_MCFGR1_PRESCALE_SHIFT;
  342. cfgr2 = base->MCFGR2;
  343. if (masterConfig->busIdleTimeout_ns)
  344. {
  345. cycles = LPI2C_GetCyclesForWidth(sourceClock_Hz, masterConfig->busIdleTimeout_ns,
  346. (LPI2C_MCFGR2_BUSIDLE_MASK >> LPI2C_MCFGR2_BUSIDLE_SHIFT), prescaler);
  347. cfgr2 &= ~LPI2C_MCFGR2_BUSIDLE_MASK;
  348. cfgr2 |= LPI2C_MCFGR2_BUSIDLE(cycles);
  349. }
  350. if (masterConfig->sdaGlitchFilterWidth_ns)
  351. {
  352. cycles = LPI2C_GetCyclesForWidth(sourceClock_Hz, masterConfig->sdaGlitchFilterWidth_ns,
  353. (LPI2C_MCFGR2_FILTSDA_MASK >> LPI2C_MCFGR2_FILTSDA_SHIFT), 1);
  354. cfgr2 &= ~LPI2C_MCFGR2_FILTSDA_MASK;
  355. cfgr2 |= LPI2C_MCFGR2_FILTSDA(cycles);
  356. }
  357. if (masterConfig->sclGlitchFilterWidth_ns)
  358. {
  359. cycles = LPI2C_GetCyclesForWidth(sourceClock_Hz, masterConfig->sclGlitchFilterWidth_ns,
  360. (LPI2C_MCFGR2_FILTSCL_MASK >> LPI2C_MCFGR2_FILTSCL_SHIFT), 1);
  361. cfgr2 &= ~LPI2C_MCFGR2_FILTSCL_MASK;
  362. cfgr2 |= LPI2C_MCFGR2_FILTSCL(cycles);
  363. }
  364. base->MCFGR2 = cfgr2;
  365. if (masterConfig->pinLowTimeout_ns)
  366. {
  367. cycles = LPI2C_GetCyclesForWidth(sourceClock_Hz, masterConfig->pinLowTimeout_ns / 256,
  368. (LPI2C_MCFGR2_BUSIDLE_MASK >> LPI2C_MCFGR2_BUSIDLE_SHIFT), prescaler);
  369. base->MCFGR3 = (base->MCFGR3 & ~LPI2C_MCFGR3_PINLOW_MASK) | LPI2C_MCFGR3_PINLOW(cycles);
  370. }
  371. LPI2C_MasterEnable(base, masterConfig->enableMaster);
  372. }
  373. void LPI2C_MasterDeinit(LPI2C_Type *base)
  374. {
  375. /* Restore to reset state. */
  376. LPI2C_MasterReset(base);
  377. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  378. uint32_t instance = LPI2C_GetInstance(base);
  379. /* Gate clock. */
  380. CLOCK_DisableClock(kLpi2cClocks[instance]);
  381. #if defined(LPI2C_PERIPH_CLOCKS)
  382. /* Gate the functional clock. */
  383. CLOCK_DisableClock(kLpi2cPeriphClocks[instance]);
  384. #endif
  385. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  386. }
  387. void LPI2C_MasterConfigureDataMatch(LPI2C_Type *base, const lpi2c_data_match_config_t *config)
  388. {
  389. /* Disable master mode. */
  390. bool wasEnabled = (base->MCR & LPI2C_MCR_MEN_MASK) >> LPI2C_MCR_MEN_SHIFT;
  391. LPI2C_MasterEnable(base, false);
  392. base->MCFGR1 = (base->MCFGR1 & ~LPI2C_MCFGR1_MATCFG_MASK) | LPI2C_MCFGR1_MATCFG(config->matchMode);
  393. base->MCFGR0 = (base->MCFGR0 & ~LPI2C_MCFGR0_RDMO_MASK) | LPI2C_MCFGR0_RDMO(config->rxDataMatchOnly);
  394. base->MDMR = LPI2C_MDMR_MATCH0(config->match0) | LPI2C_MDMR_MATCH1(config->match1);
  395. /* Restore master mode. */
  396. if (wasEnabled)
  397. {
  398. LPI2C_MasterEnable(base, true);
  399. }
  400. }
  401. void LPI2C_MasterSetBaudRate(LPI2C_Type *base, uint32_t sourceClock_Hz, uint32_t baudRate_Hz)
  402. {
  403. uint32_t prescale = 0;
  404. uint32_t bestPre = 0;
  405. uint32_t bestClkHi = 0;
  406. uint32_t absError = 0;
  407. uint32_t bestError = 0xffffffffu;
  408. uint32_t value;
  409. uint32_t clkHiCycle;
  410. uint32_t computedRate;
  411. int i;
  412. bool wasEnabled;
  413. /* Disable master mode. */
  414. wasEnabled = (base->MCR & LPI2C_MCR_MEN_MASK) >> LPI2C_MCR_MEN_SHIFT;
  415. LPI2C_MasterEnable(base, false);
  416. /* Baud rate = (sourceClock_Hz/2^prescale)/(CLKLO+1+CLKHI+1 + ROUNDDOWN((2+FILTSCL)/2^prescale) */
  417. /* Assume CLKLO = 2*CLKHI, SETHOLD = CLKHI, DATAVD = CLKHI/2. */
  418. for (prescale = 1; (prescale <= 128) && (bestError != 0); prescale = 2 * prescale)
  419. {
  420. for (clkHiCycle = 1; clkHiCycle < 32; clkHiCycle++)
  421. {
  422. if (clkHiCycle == 1)
  423. {
  424. computedRate = (sourceClock_Hz / prescale) / (1 + 3 + 2 + 2 / prescale);
  425. }
  426. else
  427. {
  428. computedRate = (sourceClock_Hz / prescale) / (3 * clkHiCycle + 2 + 2 / prescale);
  429. }
  430. absError = baudRate_Hz > computedRate ? baudRate_Hz - computedRate : computedRate - baudRate_Hz;
  431. if (absError < bestError)
  432. {
  433. bestPre = prescale;
  434. bestClkHi = clkHiCycle;
  435. bestError = absError;
  436. /* If the error is 0, then we can stop searching because we won't find a better match. */
  437. if (absError == 0)
  438. {
  439. break;
  440. }
  441. }
  442. }
  443. }
  444. /* Standard, fast, fast mode plus and ultra-fast transfers. */
  445. value = LPI2C_MCCR0_CLKHI(bestClkHi);
  446. if (bestClkHi < 2)
  447. {
  448. value |= LPI2C_MCCR0_CLKLO(3) | LPI2C_MCCR0_SETHOLD(2) | LPI2C_MCCR0_DATAVD(1);
  449. }
  450. else
  451. {
  452. value |= LPI2C_MCCR0_CLKLO(2 * bestClkHi) | LPI2C_MCCR0_SETHOLD(bestClkHi) | LPI2C_MCCR0_DATAVD(bestClkHi / 2);
  453. }
  454. base->MCCR0 = value;
  455. for (i = 0; i < 8; i++)
  456. {
  457. if (bestPre == (1U << i))
  458. {
  459. bestPre = i;
  460. break;
  461. }
  462. }
  463. base->MCFGR1 = (base->MCFGR1 & ~LPI2C_MCFGR1_PRESCALE_MASK) | LPI2C_MCFGR1_PRESCALE(bestPre);
  464. /* Restore master mode. */
  465. if (wasEnabled)
  466. {
  467. LPI2C_MasterEnable(base, true);
  468. }
  469. }
  470. status_t LPI2C_MasterStart(LPI2C_Type *base, uint8_t address, lpi2c_direction_t dir)
  471. {
  472. /* Return an error if the bus is already in use not by us. */
  473. status_t result = LPI2C_CheckForBusyBus(base);
  474. if (result)
  475. {
  476. return result;
  477. }
  478. /* Clear all flags. */
  479. LPI2C_MasterClearStatusFlags(base, kMasterClearFlags);
  480. /* Turn off auto-stop option. */
  481. base->MCFGR1 &= ~LPI2C_MCFGR1_AUTOSTOP_MASK;
  482. /* Wait until there is room in the fifo. */
  483. result = LPI2C_MasterWaitForTxReady(base);
  484. if (result)
  485. {
  486. return result;
  487. }
  488. /* Issue start command. */
  489. base->MTDR = kStartCmd | (((uint32_t)address << 1U) | (uint32_t)dir);
  490. return kStatus_Success;
  491. }
  492. status_t LPI2C_MasterStop(LPI2C_Type *base)
  493. {
  494. /* Wait until there is room in the fifo. */
  495. status_t result = LPI2C_MasterWaitForTxReady(base);
  496. if (result)
  497. {
  498. return result;
  499. }
  500. /* Send the STOP signal */
  501. base->MTDR = kStopCmd;
  502. /* Wait for the stop detected flag to set, indicating the transfer has completed on the bus. */
  503. /* Also check for errors while waiting. */
  504. #if LPI2C_WAIT_TIMEOUT
  505. uint32_t waitTimes = LPI2C_WAIT_TIMEOUT;
  506. #endif
  507. #if LPI2C_WAIT_TIMEOUT
  508. while ((result == kStatus_Success) && (--waitTimes))
  509. #else
  510. while (result == kStatus_Success)
  511. #endif
  512. {
  513. uint32_t status = LPI2C_MasterGetStatusFlags(base);
  514. /* Check for error flags. */
  515. result = LPI2C_MasterCheckAndClearError(base, status);
  516. /* Check if the stop was sent successfully. */
  517. if (status & kLPI2C_MasterStopDetectFlag)
  518. {
  519. LPI2C_MasterClearStatusFlags(base, kLPI2C_MasterStopDetectFlag);
  520. break;
  521. }
  522. }
  523. #if LPI2C_WAIT_TIMEOUT
  524. if (waitTimes == 0)
  525. {
  526. return kStatus_LPI2C_Timeout;
  527. }
  528. #endif
  529. return result;
  530. }
  531. status_t LPI2C_MasterReceive(LPI2C_Type *base, void *rxBuff, size_t rxSize)
  532. {
  533. status_t result;
  534. uint8_t *buf;
  535. assert(rxBuff);
  536. /* Handle empty read. */
  537. if (!rxSize)
  538. {
  539. return kStatus_Success;
  540. }
  541. /* Wait until there is room in the command fifo. */
  542. result = LPI2C_MasterWaitForTxReady(base);
  543. if (result)
  544. {
  545. return result;
  546. }
  547. /* Issue command to receive data. */
  548. base->MTDR = kRxDataCmd | LPI2C_MTDR_DATA(rxSize - 1);
  549. #if LPI2C_WAIT_TIMEOUT
  550. uint32_t waitTimes = LPI2C_WAIT_TIMEOUT;
  551. #endif
  552. /* Receive data */
  553. buf = (uint8_t *)rxBuff;
  554. while (rxSize--)
  555. {
  556. /* Read LPI2C receive fifo register. The register includes a flag to indicate whether */
  557. /* the FIFO is empty, so we can both get the data and check if we need to keep reading */
  558. /* using a single register read. */
  559. uint32_t value;
  560. do
  561. {
  562. /* Check for errors. */
  563. result = LPI2C_MasterCheckAndClearError(base, LPI2C_MasterGetStatusFlags(base));
  564. if (result)
  565. {
  566. return result;
  567. }
  568. value = base->MRDR;
  569. #if LPI2C_WAIT_TIMEOUT
  570. } while ((value & LPI2C_MRDR_RXEMPTY_MASK) && (--waitTimes));
  571. if (waitTimes == 0)
  572. {
  573. return kStatus_LPI2C_Timeout;
  574. }
  575. #else
  576. } while (value & LPI2C_MRDR_RXEMPTY_MASK);
  577. #endif
  578. *buf++ = value & LPI2C_MRDR_DATA_MASK;
  579. }
  580. return kStatus_Success;
  581. }
  582. status_t LPI2C_MasterSend(LPI2C_Type *base, const void *txBuff, size_t txSize)
  583. {
  584. uint8_t *buf = (uint8_t *)((void *)txBuff);
  585. assert(txBuff);
  586. /* Send data buffer */
  587. while (txSize--)
  588. {
  589. /* Wait until there is room in the fifo. This also checks for errors. */
  590. status_t result = LPI2C_MasterWaitForTxReady(base);
  591. if (result)
  592. {
  593. return result;
  594. }
  595. /* Write byte into LPI2C master data register. */
  596. base->MTDR = *buf++;
  597. }
  598. return kStatus_Success;
  599. }
  600. status_t LPI2C_MasterTransferBlocking(LPI2C_Type *base, lpi2c_master_transfer_t *transfer)
  601. {
  602. status_t result = kStatus_Success;
  603. uint16_t commandBuffer[7];
  604. uint32_t cmdCount = 0;
  605. assert(transfer);
  606. assert(transfer->subaddressSize <= sizeof(transfer->subaddress));
  607. /* Return an error if the bus is already in use not by us. */
  608. result = LPI2C_CheckForBusyBus(base);
  609. if (result)
  610. {
  611. return result;
  612. }
  613. /* Clear all flags. */
  614. LPI2C_MasterClearStatusFlags(base, kMasterClearFlags);
  615. /* Turn off auto-stop option. */
  616. base->MCFGR1 &= ~LPI2C_MCFGR1_AUTOSTOP_MASK;
  617. lpi2c_direction_t direction = transfer->subaddressSize ? kLPI2C_Write : transfer->direction;
  618. if (!(transfer->flags & kLPI2C_TransferNoStartFlag))
  619. {
  620. commandBuffer[cmdCount++] =
  621. (uint16_t)kStartCmd | (uint16_t)((uint16_t)((uint16_t)transfer->slaveAddress << 1U) | (uint16_t)direction);
  622. }
  623. /* Subaddress, MSB first. */
  624. if (transfer->subaddressSize)
  625. {
  626. uint32_t subaddressRemaining = transfer->subaddressSize;
  627. while (subaddressRemaining--)
  628. {
  629. uint8_t subaddressByte = (transfer->subaddress >> (8 * subaddressRemaining)) & 0xff;
  630. commandBuffer[cmdCount++] = subaddressByte;
  631. }
  632. }
  633. /* Reads need special handling. */
  634. if ((transfer->dataSize) && (transfer->direction == kLPI2C_Read))
  635. {
  636. /* Need to send repeated start if switching directions to read. */
  637. if (direction == kLPI2C_Write)
  638. {
  639. commandBuffer[cmdCount++] =
  640. (uint16_t)kStartCmd |
  641. (uint16_t)((uint16_t)((uint16_t)transfer->slaveAddress << 1U) | (uint16_t)kLPI2C_Read);
  642. }
  643. }
  644. /* Send command buffer */
  645. uint32_t index = 0;
  646. while (cmdCount--)
  647. {
  648. /* Wait until there is room in the fifo. This also checks for errors. */
  649. result = LPI2C_MasterWaitForTxReady(base);
  650. if (result)
  651. {
  652. return result;
  653. }
  654. /* Write byte into LPI2C master data register. */
  655. base->MTDR = commandBuffer[index];
  656. index++;
  657. }
  658. /* Transmit data. */
  659. if ((transfer->direction == kLPI2C_Write) && (transfer->dataSize > 0))
  660. {
  661. /* Send Data. */
  662. result = LPI2C_MasterSend(base, transfer->data, transfer->dataSize);
  663. }
  664. /* Receive Data. */
  665. if ((transfer->direction == kLPI2C_Read) && (transfer->dataSize > 0))
  666. {
  667. result = LPI2C_MasterReceive(base, transfer->data, transfer->dataSize);
  668. }
  669. if (result)
  670. {
  671. return result;
  672. }
  673. if ((transfer->flags & kLPI2C_TransferNoStopFlag) == 0)
  674. {
  675. result = LPI2C_MasterStop(base);
  676. }
  677. return result;
  678. }
  679. void LPI2C_MasterTransferCreateHandle(LPI2C_Type *base,
  680. lpi2c_master_handle_t *handle,
  681. lpi2c_master_transfer_callback_t callback,
  682. void *userData)
  683. {
  684. uint32_t instance;
  685. assert(handle);
  686. /* Clear out the handle. */
  687. memset(handle, 0, sizeof(*handle));
  688. /* Look up instance number */
  689. instance = LPI2C_GetInstance(base);
  690. /* Save base and instance. */
  691. handle->completionCallback = callback;
  692. handle->userData = userData;
  693. /* Save this handle for IRQ use. */
  694. s_lpi2cMasterHandle[instance] = handle;
  695. /* Set irq handler. */
  696. s_lpi2cMasterIsr = LPI2C_MasterTransferHandleIRQ;
  697. /* Clear internal IRQ enables and enable NVIC IRQ. */
  698. LPI2C_MasterDisableInterrupts(base, kMasterIrqFlags);
  699. EnableIRQ(kLpi2cIrqs[instance]);
  700. }
  701. /*!
  702. * @brief Execute states until FIFOs are exhausted.
  703. * @param handle Master nonblocking driver handle.
  704. * @param[out] isDone Set to true if the transfer has completed.
  705. * @retval #kStatus_Success
  706. * @retval #kStatus_LPI2C_PinLowTimeout
  707. * @retval #kStatus_LPI2C_ArbitrationLost
  708. * @retval #kStatus_LPI2C_Nak
  709. * @retval #kStatus_LPI2C_FifoError
  710. */
  711. static status_t LPI2C_RunTransferStateMachine(LPI2C_Type *base, lpi2c_master_handle_t *handle, bool *isDone)
  712. {
  713. uint32_t status;
  714. status_t result = kStatus_Success;
  715. lpi2c_master_transfer_t *xfer;
  716. size_t txCount;
  717. size_t rxCount;
  718. size_t txFifoSize = FSL_FEATURE_LPI2C_FIFO_SIZEn(base);
  719. bool state_complete = false;
  720. /* Set default isDone return value. */
  721. *isDone = false;
  722. /* Check for errors. */
  723. status = LPI2C_MasterGetStatusFlags(base);
  724. result = LPI2C_MasterCheckAndClearError(base, status);
  725. if (result)
  726. {
  727. return result;
  728. }
  729. /* Get pointer to private data. */
  730. xfer = &handle->transfer;
  731. /* Get fifo counts and compute room in tx fifo. */
  732. LPI2C_MasterGetFifoCounts(base, &rxCount, &txCount);
  733. txCount = txFifoSize - txCount;
  734. while (!state_complete)
  735. {
  736. /* Execute the state. */
  737. switch (handle->state)
  738. {
  739. case kSendCommandState:
  740. {
  741. /* Make sure there is room in the tx fifo for the next command. */
  742. if (!txCount--)
  743. {
  744. state_complete = true;
  745. break;
  746. }
  747. /* Issue command. buf is a uint8_t* pointing at the uint16 command array. */
  748. base->MTDR = *(uint16_t *)handle->buf;
  749. handle->buf += sizeof(uint16_t);
  750. /* Count down until all commands are sent. */
  751. if (--handle->remainingBytes == 0)
  752. {
  753. /* Choose next state and set up buffer pointer and count. */
  754. if (xfer->dataSize)
  755. {
  756. /* Either a send or receive transfer is next. */
  757. handle->state = kTransferDataState;
  758. handle->buf = (uint8_t *)xfer->data;
  759. handle->remainingBytes = xfer->dataSize;
  760. if (xfer->direction == kLPI2C_Read)
  761. {
  762. /* Disable TX interrupt */
  763. LPI2C_MasterDisableInterrupts(base, kLPI2C_MasterTxReadyFlag);
  764. }
  765. }
  766. else
  767. {
  768. /* No transfer, so move to stop state. */
  769. handle->state = kStopState;
  770. }
  771. }
  772. break;
  773. }
  774. case kIssueReadCommandState:
  775. /* Make sure there is room in the tx fifo for the read command. */
  776. if (!txCount--)
  777. {
  778. state_complete = true;
  779. break;
  780. }
  781. base->MTDR = kRxDataCmd | LPI2C_MTDR_DATA(xfer->dataSize - 1);
  782. /* Move to transfer state. */
  783. handle->state = kTransferDataState;
  784. if (xfer->direction == kLPI2C_Read)
  785. {
  786. /* Disable TX interrupt */
  787. LPI2C_MasterDisableInterrupts(base, kLPI2C_MasterTxReadyFlag);
  788. }
  789. break;
  790. case kTransferDataState:
  791. if (xfer->direction == kLPI2C_Write)
  792. {
  793. /* Make sure there is room in the tx fifo. */
  794. if (!txCount--)
  795. {
  796. state_complete = true;
  797. break;
  798. }
  799. /* Put byte to send in fifo. */
  800. base->MTDR = *(handle->buf)++;
  801. }
  802. else
  803. {
  804. /* XXX handle receive sizes > 256, use kIssueReadCommandState */
  805. /* Make sure there is data in the rx fifo. */
  806. if (!rxCount--)
  807. {
  808. state_complete = true;
  809. break;
  810. }
  811. /* Read byte from fifo. */
  812. *(handle->buf)++ = base->MRDR & LPI2C_MRDR_DATA_MASK;
  813. }
  814. /* Move to stop when the transfer is done. */
  815. if (--handle->remainingBytes == 0)
  816. {
  817. handle->state = kStopState;
  818. }
  819. break;
  820. case kStopState:
  821. /* Only issue a stop transition if the caller requested it. */
  822. if ((xfer->flags & kLPI2C_TransferNoStopFlag) == 0)
  823. {
  824. /* Make sure there is room in the tx fifo for the stop command. */
  825. if (!txCount--)
  826. {
  827. state_complete = true;
  828. break;
  829. }
  830. base->MTDR = kStopCmd;
  831. }
  832. else
  833. {
  834. /* Caller doesn't want to send a stop, so we're done now. */
  835. *isDone = true;
  836. state_complete = true;
  837. break;
  838. }
  839. handle->state = kWaitForCompletionState;
  840. break;
  841. case kWaitForCompletionState:
  842. /* We stay in this state until the stop state is detected. */
  843. if (status & kLPI2C_MasterStopDetectFlag)
  844. {
  845. *isDone = true;
  846. }
  847. state_complete = true;
  848. break;
  849. default:
  850. assert(false);
  851. break;
  852. }
  853. }
  854. return result;
  855. }
  856. /*!
  857. * @brief Prepares the transfer state machine and fills in the command buffer.
  858. * @param handle Master nonblocking driver handle.
  859. */
  860. static void LPI2C_InitTransferStateMachine(lpi2c_master_handle_t *handle)
  861. {
  862. lpi2c_master_transfer_t *xfer = &handle->transfer;
  863. /* Handle no start option. */
  864. if (xfer->flags & kLPI2C_TransferNoStartFlag)
  865. {
  866. if (xfer->direction == kLPI2C_Read)
  867. {
  868. /* Need to issue read command first. */
  869. handle->state = kIssueReadCommandState;
  870. }
  871. else
  872. {
  873. /* Start immediately in the data transfer state. */
  874. handle->state = kTransferDataState;
  875. }
  876. handle->buf = (uint8_t *)xfer->data;
  877. handle->remainingBytes = xfer->dataSize;
  878. }
  879. else
  880. {
  881. uint16_t *cmd = (uint16_t *)&handle->commandBuffer;
  882. uint32_t cmdCount = 0;
  883. /* Initial direction depends on whether a subaddress was provided, and of course the actual */
  884. /* data transfer direction. */
  885. lpi2c_direction_t direction = xfer->subaddressSize ? kLPI2C_Write : xfer->direction;
  886. /* Start command. */
  887. cmd[cmdCount++] =
  888. (uint16_t)kStartCmd | (uint16_t)((uint16_t)((uint16_t)xfer->slaveAddress << 1U) | (uint16_t)direction);
  889. /* Subaddress, MSB first. */
  890. if (xfer->subaddressSize)
  891. {
  892. uint32_t subaddressRemaining = xfer->subaddressSize;
  893. while (subaddressRemaining--)
  894. {
  895. uint8_t subaddressByte = (xfer->subaddress >> (8 * subaddressRemaining)) & 0xff;
  896. cmd[cmdCount++] = subaddressByte;
  897. }
  898. }
  899. /* Reads need special handling. */
  900. if ((xfer->dataSize) && (xfer->direction == kLPI2C_Read))
  901. {
  902. /* Need to send repeated start if switching directions to read. */
  903. if (direction == kLPI2C_Write)
  904. {
  905. cmd[cmdCount++] = (uint16_t)kStartCmd |
  906. (uint16_t)((uint16_t)((uint16_t)xfer->slaveAddress << 1U) | (uint16_t)kLPI2C_Read);
  907. }
  908. /* Read command. */
  909. cmd[cmdCount++] = kRxDataCmd | LPI2C_MTDR_DATA(xfer->dataSize - 1);
  910. }
  911. /* Set up state machine for transferring the commands. */
  912. handle->state = kSendCommandState;
  913. handle->remainingBytes = cmdCount;
  914. handle->buf = (uint8_t *)&handle->commandBuffer;
  915. }
  916. }
  917. status_t LPI2C_MasterTransferNonBlocking(LPI2C_Type *base,
  918. lpi2c_master_handle_t *handle,
  919. lpi2c_master_transfer_t *transfer)
  920. {
  921. status_t result;
  922. assert(handle);
  923. assert(transfer);
  924. assert(transfer->subaddressSize <= sizeof(transfer->subaddress));
  925. /* Return busy if another transaction is in progress. */
  926. if (handle->state != kIdleState)
  927. {
  928. return kStatus_LPI2C_Busy;
  929. }
  930. /* Return an error if the bus is already in use not by us. */
  931. result = LPI2C_CheckForBusyBus(base);
  932. if (result)
  933. {
  934. return result;
  935. }
  936. /* Disable LPI2C IRQ sources while we configure stuff. */
  937. LPI2C_MasterDisableInterrupts(base, kMasterIrqFlags);
  938. /* Save transfer into handle. */
  939. handle->transfer = *transfer;
  940. /* Generate commands to send. */
  941. LPI2C_InitTransferStateMachine(handle);
  942. /* Clear all flags. */
  943. LPI2C_MasterClearStatusFlags(base, kMasterClearFlags);
  944. /* Turn off auto-stop option. */
  945. base->MCFGR1 &= ~LPI2C_MCFGR1_AUTOSTOP_MASK;
  946. /* Enable LPI2C internal IRQ sources. NVIC IRQ was enabled in CreateHandle() */
  947. LPI2C_MasterEnableInterrupts(base, kMasterIrqFlags);
  948. return result;
  949. }
  950. status_t LPI2C_MasterTransferGetCount(LPI2C_Type *base, lpi2c_master_handle_t *handle, size_t *count)
  951. {
  952. assert(handle);
  953. if (!count)
  954. {
  955. return kStatus_InvalidArgument;
  956. }
  957. /* Catch when there is not an active transfer. */
  958. if (handle->state == kIdleState)
  959. {
  960. *count = 0;
  961. return kStatus_NoTransferInProgress;
  962. }
  963. uint8_t state;
  964. uint16_t remainingBytes;
  965. uint32_t dataSize;
  966. /* Cache some fields with IRQs disabled. This ensures all field values */
  967. /* are synchronized with each other during an ongoing transfer. */
  968. uint32_t irqs = LPI2C_MasterGetEnabledInterrupts(base);
  969. LPI2C_MasterDisableInterrupts(base, irqs);
  970. state = handle->state;
  971. remainingBytes = handle->remainingBytes;
  972. dataSize = handle->transfer.dataSize;
  973. LPI2C_MasterEnableInterrupts(base, irqs);
  974. /* Get transfer count based on current transfer state. */
  975. switch (state)
  976. {
  977. case kIdleState:
  978. case kSendCommandState:
  979. case kIssueReadCommandState: /* XXX return correct value for this state when >256 reads are supported */
  980. *count = 0;
  981. break;
  982. case kTransferDataState:
  983. *count = dataSize - remainingBytes;
  984. break;
  985. case kStopState:
  986. case kWaitForCompletionState:
  987. default:
  988. *count = dataSize;
  989. break;
  990. }
  991. return kStatus_Success;
  992. }
  993. void LPI2C_MasterTransferAbort(LPI2C_Type *base, lpi2c_master_handle_t *handle)
  994. {
  995. if (handle->state != kIdleState)
  996. {
  997. /* Disable internal IRQ enables. */
  998. LPI2C_MasterDisableInterrupts(base, kMasterIrqFlags);
  999. /* Reset fifos. */
  1000. base->MCR |= LPI2C_MCR_RRF_MASK | LPI2C_MCR_RTF_MASK;
  1001. /* Send a stop command to finalize the transfer. */
  1002. base->MTDR = kStopCmd;
  1003. /* Reset handle. */
  1004. handle->state = kIdleState;
  1005. }
  1006. }
  1007. void LPI2C_MasterTransferHandleIRQ(LPI2C_Type *base, lpi2c_master_handle_t *handle)
  1008. {
  1009. bool isDone;
  1010. status_t result;
  1011. /* Don't do anything if we don't have a valid handle. */
  1012. if (!handle)
  1013. {
  1014. return;
  1015. }
  1016. if (handle->state == kIdleState)
  1017. {
  1018. return;
  1019. }
  1020. result = LPI2C_RunTransferStateMachine(base, handle, &isDone);
  1021. if (isDone || (result != kStatus_Success))
  1022. {
  1023. /* XXX need to handle data that may be in rx fifo below watermark level? */
  1024. /* XXX handle error, terminate xfer */
  1025. /* Disable internal IRQ enables. */
  1026. LPI2C_MasterDisableInterrupts(base, kMasterIrqFlags);
  1027. /* Set handle to idle state. */
  1028. handle->state = kIdleState;
  1029. /* Invoke callback. */
  1030. if (handle->completionCallback)
  1031. {
  1032. handle->completionCallback(base, handle, result, handle->userData);
  1033. }
  1034. }
  1035. }
  1036. void LPI2C_SlaveGetDefaultConfig(lpi2c_slave_config_t *slaveConfig)
  1037. {
  1038. slaveConfig->enableSlave = true;
  1039. slaveConfig->address0 = 0U;
  1040. slaveConfig->address1 = 0U;
  1041. slaveConfig->addressMatchMode = kLPI2C_MatchAddress0;
  1042. slaveConfig->filterDozeEnable = true;
  1043. slaveConfig->filterEnable = true;
  1044. slaveConfig->enableGeneralCall = false;
  1045. slaveConfig->sclStall.enableAck = false;
  1046. slaveConfig->sclStall.enableTx = true;
  1047. slaveConfig->sclStall.enableRx = true;
  1048. slaveConfig->sclStall.enableAddress = false;
  1049. slaveConfig->ignoreAck = false;
  1050. slaveConfig->enableReceivedAddressRead = false;
  1051. slaveConfig->sdaGlitchFilterWidth_ns = 0; /* TODO determine default width values */
  1052. slaveConfig->sclGlitchFilterWidth_ns = 0;
  1053. slaveConfig->dataValidDelay_ns = 0;
  1054. slaveConfig->clockHoldTime_ns = 0;
  1055. }
  1056. void LPI2C_SlaveInit(LPI2C_Type *base, const lpi2c_slave_config_t *slaveConfig, uint32_t sourceClock_Hz)
  1057. {
  1058. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  1059. uint32_t instance = LPI2C_GetInstance(base);
  1060. /* Ungate the clock. */
  1061. CLOCK_EnableClock(kLpi2cClocks[instance]);
  1062. #if defined(LPI2C_PERIPH_CLOCKS)
  1063. /* Ungate the functional clock in initialize function. */
  1064. CLOCK_EnableClock(kLpi2cPeriphClocks[instance]);
  1065. #endif
  1066. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  1067. /* Restore to reset conditions. */
  1068. LPI2C_SlaveReset(base);
  1069. /* Configure peripheral. */
  1070. base->SAMR = LPI2C_SAMR_ADDR0(slaveConfig->address0) | LPI2C_SAMR_ADDR1(slaveConfig->address1);
  1071. base->SCFGR1 =
  1072. LPI2C_SCFGR1_ADDRCFG(slaveConfig->addressMatchMode) | LPI2C_SCFGR1_IGNACK(slaveConfig->ignoreAck) |
  1073. LPI2C_SCFGR1_RXCFG(slaveConfig->enableReceivedAddressRead) | LPI2C_SCFGR1_GCEN(slaveConfig->enableGeneralCall) |
  1074. LPI2C_SCFGR1_ACKSTALL(slaveConfig->sclStall.enableAck) | LPI2C_SCFGR1_TXDSTALL(slaveConfig->sclStall.enableTx) |
  1075. LPI2C_SCFGR1_RXSTALL(slaveConfig->sclStall.enableRx) |
  1076. LPI2C_SCFGR1_ADRSTALL(slaveConfig->sclStall.enableAddress);
  1077. base->SCFGR2 =
  1078. LPI2C_SCFGR2_FILTSDA(LPI2C_GetCyclesForWidth(sourceClock_Hz, slaveConfig->sdaGlitchFilterWidth_ns,
  1079. (LPI2C_SCFGR2_FILTSDA_MASK >> LPI2C_SCFGR2_FILTSDA_SHIFT), 1)) |
  1080. LPI2C_SCFGR2_FILTSCL(LPI2C_GetCyclesForWidth(sourceClock_Hz, slaveConfig->sclGlitchFilterWidth_ns,
  1081. (LPI2C_SCFGR2_FILTSCL_MASK >> LPI2C_SCFGR2_FILTSCL_SHIFT), 1)) |
  1082. LPI2C_SCFGR2_DATAVD(LPI2C_GetCyclesForWidth(sourceClock_Hz, slaveConfig->dataValidDelay_ns,
  1083. (LPI2C_SCFGR2_DATAVD_MASK >> LPI2C_SCFGR2_DATAVD_SHIFT), 1)) |
  1084. LPI2C_SCFGR2_CLKHOLD(LPI2C_GetCyclesForWidth(sourceClock_Hz, slaveConfig->clockHoldTime_ns,
  1085. (LPI2C_SCFGR2_CLKHOLD_MASK >> LPI2C_SCFGR2_CLKHOLD_SHIFT), 1));
  1086. /* Save SCR to last so we don't enable slave until it is configured */
  1087. base->SCR = LPI2C_SCR_FILTDZ(slaveConfig->filterDozeEnable) | LPI2C_SCR_FILTEN(slaveConfig->filterEnable) |
  1088. LPI2C_SCR_SEN(slaveConfig->enableSlave);
  1089. }
  1090. void LPI2C_SlaveDeinit(LPI2C_Type *base)
  1091. {
  1092. LPI2C_SlaveReset(base);
  1093. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  1094. uint32_t instance = LPI2C_GetInstance(base);
  1095. /* Gate the clock. */
  1096. CLOCK_DisableClock(kLpi2cClocks[instance]);
  1097. #if defined(LPI2C_PERIPH_CLOCKS)
  1098. /* Gate the functional clock. */
  1099. CLOCK_DisableClock(kLpi2cPeriphClocks[instance]);
  1100. #endif
  1101. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  1102. }
  1103. /*!
  1104. * @brief Convert provided flags to status code, and clear any errors if present.
  1105. * @param base The LPI2C peripheral base address.
  1106. * @param status Current status flags value that will be checked.
  1107. * @retval #kStatus_Success
  1108. * @retval #kStatus_LPI2C_BitError
  1109. * @retval #kStatus_LPI2C_FifoError
  1110. */
  1111. static status_t LPI2C_SlaveCheckAndClearError(LPI2C_Type *base, uint32_t flags)
  1112. {
  1113. status_t result = kStatus_Success;
  1114. flags &= kSlaveErrorFlags;
  1115. if (flags)
  1116. {
  1117. if (flags & kLPI2C_SlaveBitErrFlag)
  1118. {
  1119. result = kStatus_LPI2C_BitError;
  1120. }
  1121. else if (flags & kLPI2C_SlaveFifoErrFlag)
  1122. {
  1123. result = kStatus_LPI2C_FifoError;
  1124. }
  1125. else
  1126. {
  1127. assert(false);
  1128. }
  1129. /* Clear the errors. */
  1130. LPI2C_SlaveClearStatusFlags(base, flags);
  1131. }
  1132. return result;
  1133. }
  1134. status_t LPI2C_SlaveSend(LPI2C_Type *base, const void *txBuff, size_t txSize, size_t *actualTxSize)
  1135. {
  1136. uint8_t *buf = (uint8_t *)((void *)txBuff);
  1137. size_t remaining = txSize;
  1138. assert(txBuff);
  1139. #if LPI2C_WAIT_TIMEOUT
  1140. uint32_t waitTimes = LPI2C_WAIT_TIMEOUT;
  1141. #endif
  1142. while (remaining)
  1143. {
  1144. uint32_t flags;
  1145. status_t result;
  1146. /* Wait until we can transmit. */
  1147. do
  1148. {
  1149. /* Check for errors */
  1150. flags = LPI2C_SlaveGetStatusFlags(base);
  1151. result = LPI2C_SlaveCheckAndClearError(base, flags);
  1152. if (result)
  1153. {
  1154. if (actualTxSize)
  1155. {
  1156. *actualTxSize = txSize - remaining;
  1157. }
  1158. return result;
  1159. }
  1160. #if LPI2C_WAIT_TIMEOUT
  1161. } while (
  1162. (!(flags & (kLPI2C_SlaveTxReadyFlag | kLPI2C_SlaveStopDetectFlag | kLPI2C_SlaveRepeatedStartDetectFlag))) &&
  1163. (--waitTimes));
  1164. if (waitTimes == 0)
  1165. {
  1166. return kStatus_LPI2C_Timeout;
  1167. }
  1168. #else
  1169. } while (
  1170. !(flags & (kLPI2C_SlaveTxReadyFlag | kLPI2C_SlaveStopDetectFlag | kLPI2C_SlaveRepeatedStartDetectFlag)));
  1171. #endif
  1172. /* Send a byte. */
  1173. if (flags & kLPI2C_SlaveTxReadyFlag)
  1174. {
  1175. base->STDR = *buf++;
  1176. --remaining;
  1177. }
  1178. /* Exit loop if we see a stop or restart */
  1179. if (flags & (kLPI2C_SlaveStopDetectFlag | kLPI2C_SlaveRepeatedStartDetectFlag))
  1180. {
  1181. LPI2C_SlaveClearStatusFlags(base, kLPI2C_SlaveStopDetectFlag | kLPI2C_SlaveRepeatedStartDetectFlag);
  1182. break;
  1183. }
  1184. }
  1185. if (actualTxSize)
  1186. {
  1187. *actualTxSize = txSize - remaining;
  1188. }
  1189. return kStatus_Success;
  1190. }
  1191. status_t LPI2C_SlaveReceive(LPI2C_Type *base, void *rxBuff, size_t rxSize, size_t *actualRxSize)
  1192. {
  1193. uint8_t *buf = (uint8_t *)rxBuff;
  1194. size_t remaining = rxSize;
  1195. assert(rxBuff);
  1196. #if LPI2C_WAIT_TIMEOUT
  1197. uint32_t waitTimes = LPI2C_WAIT_TIMEOUT;
  1198. #endif
  1199. while (remaining)
  1200. {
  1201. uint32_t flags;
  1202. status_t result;
  1203. /* Wait until we can receive. */
  1204. do
  1205. {
  1206. /* Check for errors */
  1207. flags = LPI2C_SlaveGetStatusFlags(base);
  1208. result = LPI2C_SlaveCheckAndClearError(base, flags);
  1209. if (result)
  1210. {
  1211. if (actualRxSize)
  1212. {
  1213. *actualRxSize = rxSize - remaining;
  1214. }
  1215. return result;
  1216. }
  1217. #if LPI2C_WAIT_TIMEOUT
  1218. } while (
  1219. (!(flags & (kLPI2C_SlaveRxReadyFlag | kLPI2C_SlaveStopDetectFlag | kLPI2C_SlaveRepeatedStartDetectFlag))) &&
  1220. (--waitTimes));
  1221. if (waitTimes == 0)
  1222. {
  1223. return kStatus_LPI2C_Timeout;
  1224. }
  1225. #else
  1226. } while (
  1227. !(flags & (kLPI2C_SlaveRxReadyFlag | kLPI2C_SlaveStopDetectFlag | kLPI2C_SlaveRepeatedStartDetectFlag)));
  1228. #endif
  1229. /* Receive a byte. */
  1230. if (flags & kLPI2C_SlaveRxReadyFlag)
  1231. {
  1232. *buf++ = base->SRDR & LPI2C_SRDR_DATA_MASK;
  1233. --remaining;
  1234. }
  1235. /* Exit loop if we see a stop or restart */
  1236. if (flags & (kLPI2C_SlaveStopDetectFlag | kLPI2C_SlaveRepeatedStartDetectFlag))
  1237. {
  1238. LPI2C_SlaveClearStatusFlags(base, kLPI2C_SlaveStopDetectFlag | kLPI2C_SlaveRepeatedStartDetectFlag);
  1239. break;
  1240. }
  1241. }
  1242. if (actualRxSize)
  1243. {
  1244. *actualRxSize = rxSize - remaining;
  1245. }
  1246. return kStatus_Success;
  1247. }
  1248. void LPI2C_SlaveTransferCreateHandle(LPI2C_Type *base,
  1249. lpi2c_slave_handle_t *handle,
  1250. lpi2c_slave_transfer_callback_t callback,
  1251. void *userData)
  1252. {
  1253. uint32_t instance;
  1254. assert(handle);
  1255. /* Clear out the handle. */
  1256. memset(handle, 0, sizeof(*handle));
  1257. /* Look up instance number */
  1258. instance = LPI2C_GetInstance(base);
  1259. /* Save base and instance. */
  1260. handle->callback = callback;
  1261. handle->userData = userData;
  1262. /* Save this handle for IRQ use. */
  1263. s_lpi2cSlaveHandle[instance] = handle;
  1264. /* Set irq handler. */
  1265. s_lpi2cSlaveIsr = LPI2C_SlaveTransferHandleIRQ;
  1266. /* Clear internal IRQ enables and enable NVIC IRQ. */
  1267. LPI2C_SlaveDisableInterrupts(base, kSlaveIrqFlags);
  1268. EnableIRQ(kLpi2cIrqs[instance]);
  1269. /* Nack by default. */
  1270. base->STAR = LPI2C_STAR_TXNACK_MASK;
  1271. }
  1272. status_t LPI2C_SlaveTransferNonBlocking(LPI2C_Type *base, lpi2c_slave_handle_t *handle, uint32_t eventMask)
  1273. {
  1274. uint32_t status;
  1275. assert(handle);
  1276. /* Return busy if another transaction is in progress. */
  1277. if (handle->isBusy)
  1278. {
  1279. return kStatus_LPI2C_Busy;
  1280. }
  1281. /* Return an error if the bus is already in use not by us. */
  1282. status = LPI2C_SlaveGetStatusFlags(base);
  1283. if ((status & kLPI2C_SlaveBusBusyFlag) && (!(status & kLPI2C_SlaveBusyFlag)))
  1284. {
  1285. return kStatus_LPI2C_Busy;
  1286. }
  1287. /* Disable LPI2C IRQ sources while we configure stuff. */
  1288. LPI2C_SlaveDisableInterrupts(base, kSlaveIrqFlags);
  1289. /* Clear transfer in handle. */
  1290. memset(&handle->transfer, 0, sizeof(handle->transfer));
  1291. /* Record that we're busy. */
  1292. handle->isBusy = true;
  1293. /* Set up event mask. tx and rx are always enabled. */
  1294. handle->eventMask = eventMask | kLPI2C_SlaveTransmitEvent | kLPI2C_SlaveReceiveEvent;
  1295. /* Ack by default. */
  1296. base->STAR = 0;
  1297. /* Clear all flags. */
  1298. LPI2C_SlaveClearStatusFlags(base, kSlaveClearFlags);
  1299. /* Enable LPI2C internal IRQ sources. NVIC IRQ was enabled in CreateHandle() */
  1300. LPI2C_SlaveEnableInterrupts(base, kSlaveIrqFlags);
  1301. return kStatus_Success;
  1302. }
  1303. status_t LPI2C_SlaveTransferGetCount(LPI2C_Type *base, lpi2c_slave_handle_t *handle, size_t *count)
  1304. {
  1305. assert(handle);
  1306. if (!count)
  1307. {
  1308. return kStatus_InvalidArgument;
  1309. }
  1310. /* Catch when there is not an active transfer. */
  1311. if (!handle->isBusy)
  1312. {
  1313. *count = 0;
  1314. return kStatus_NoTransferInProgress;
  1315. }
  1316. /* For an active transfer, just return the count from the handle. */
  1317. *count = handle->transferredCount;
  1318. return kStatus_Success;
  1319. }
  1320. void LPI2C_SlaveTransferAbort(LPI2C_Type *base, lpi2c_slave_handle_t *handle)
  1321. {
  1322. assert(handle);
  1323. /* Return idle if no transaction is in progress. */
  1324. if (handle->isBusy)
  1325. {
  1326. /* Disable LPI2C IRQ sources. */
  1327. LPI2C_SlaveDisableInterrupts(base, kSlaveIrqFlags);
  1328. /* Nack by default. */
  1329. base->STAR = LPI2C_STAR_TXNACK_MASK;
  1330. /* Reset transfer info. */
  1331. memset(&handle->transfer, 0, sizeof(handle->transfer));
  1332. /* We're no longer busy. */
  1333. handle->isBusy = false;
  1334. }
  1335. }
  1336. void LPI2C_SlaveTransferHandleIRQ(LPI2C_Type *base, lpi2c_slave_handle_t *handle)
  1337. {
  1338. uint32_t flags;
  1339. lpi2c_slave_transfer_t *xfer;
  1340. /* Check for a valid handle in case of a spurious interrupt. */
  1341. if (!handle)
  1342. {
  1343. return;
  1344. }
  1345. xfer = &handle->transfer;
  1346. /* Get status flags. */
  1347. flags = LPI2C_SlaveGetStatusFlags(base);
  1348. if (flags & (kLPI2C_SlaveBitErrFlag | kLPI2C_SlaveFifoErrFlag))
  1349. {
  1350. xfer->event = kLPI2C_SlaveCompletionEvent;
  1351. xfer->completionStatus = LPI2C_SlaveCheckAndClearError(base, flags);
  1352. if ((handle->eventMask & kLPI2C_SlaveCompletionEvent) && (handle->callback))
  1353. {
  1354. handle->callback(base, xfer, handle->userData);
  1355. }
  1356. return;
  1357. }
  1358. if (flags & (kLPI2C_SlaveRepeatedStartDetectFlag | kLPI2C_SlaveStopDetectFlag))
  1359. {
  1360. xfer->event = (flags & kLPI2C_SlaveRepeatedStartDetectFlag) ? kLPI2C_SlaveRepeatedStartEvent :
  1361. kLPI2C_SlaveCompletionEvent;
  1362. xfer->receivedAddress = 0;
  1363. xfer->completionStatus = kStatus_Success;
  1364. xfer->transferredCount = handle->transferredCount;
  1365. if (xfer->event == kLPI2C_SlaveCompletionEvent)
  1366. {
  1367. handle->isBusy = false;
  1368. }
  1369. if (handle->wasTransmit)
  1370. {
  1371. /* Subtract one from the transmit count to offset the fact that LPI2C asserts the */
  1372. /* tx flag before it sees the nack from the master-receiver, thus causing one more */
  1373. /* count that the master actually receives. */
  1374. --xfer->transferredCount;
  1375. handle->wasTransmit = false;
  1376. }
  1377. /* Clear the flag. */
  1378. LPI2C_SlaveClearStatusFlags(base, flags & (kLPI2C_SlaveRepeatedStartDetectFlag | kLPI2C_SlaveStopDetectFlag));
  1379. /* Revert to sending an Ack by default, in case we sent a Nack for receive. */
  1380. base->STAR = 0;
  1381. if ((handle->eventMask & xfer->event) && (handle->callback))
  1382. {
  1383. handle->callback(base, xfer, handle->userData);
  1384. }
  1385. /* Clean up transfer info on completion, after the callback has been invoked. */
  1386. memset(&handle->transfer, 0, sizeof(handle->transfer));
  1387. }
  1388. if (flags & kLPI2C_SlaveAddressValidFlag)
  1389. {
  1390. xfer->event = kLPI2C_SlaveAddressMatchEvent;
  1391. xfer->receivedAddress = base->SASR & LPI2C_SASR_RADDR_MASK;
  1392. if ((handle->eventMask & kLPI2C_SlaveAddressMatchEvent) && (handle->callback))
  1393. {
  1394. handle->callback(base, xfer, handle->userData);
  1395. }
  1396. }
  1397. if (flags & kLPI2C_SlaveTransmitAckFlag)
  1398. {
  1399. xfer->event = kLPI2C_SlaveTransmitAckEvent;
  1400. if ((handle->eventMask & kLPI2C_SlaveTransmitAckEvent) && (handle->callback))
  1401. {
  1402. handle->callback(base, xfer, handle->userData);
  1403. }
  1404. }
  1405. /* Handle transmit and receive. */
  1406. if (flags & kLPI2C_SlaveTxReadyFlag)
  1407. {
  1408. handle->wasTransmit = true;
  1409. /* If we're out of data, invoke callback to get more. */
  1410. if ((!xfer->data) || (!xfer->dataSize))
  1411. {
  1412. xfer->event = kLPI2C_SlaveTransmitEvent;
  1413. if (handle->callback)
  1414. {
  1415. handle->callback(base, xfer, handle->userData);
  1416. }
  1417. /* Clear the transferred count now that we have a new buffer. */
  1418. handle->transferredCount = 0;
  1419. }
  1420. /* Transmit a byte. */
  1421. if ((xfer->data) && (xfer->dataSize))
  1422. {
  1423. base->STDR = *xfer->data++;
  1424. --xfer->dataSize;
  1425. ++handle->transferredCount;
  1426. }
  1427. }
  1428. if (flags & kLPI2C_SlaveRxReadyFlag)
  1429. {
  1430. /* If we're out of room in the buffer, invoke callback to get another. */
  1431. if ((!xfer->data) || (!xfer->dataSize))
  1432. {
  1433. xfer->event = kLPI2C_SlaveReceiveEvent;
  1434. if (handle->callback)
  1435. {
  1436. handle->callback(base, xfer, handle->userData);
  1437. }
  1438. /* Clear the transferred count now that we have a new buffer. */
  1439. handle->transferredCount = 0;
  1440. }
  1441. /* Receive a byte. */
  1442. if ((xfer->data) && (xfer->dataSize))
  1443. {
  1444. *xfer->data++ = base->SRDR;
  1445. --xfer->dataSize;
  1446. ++handle->transferredCount;
  1447. }
  1448. else
  1449. {
  1450. /* We don't have any room to receive more data, so send a nack. */
  1451. base->STAR = LPI2C_STAR_TXNACK_MASK;
  1452. }
  1453. }
  1454. }
  1455. /*!
  1456. * @brief Shared IRQ handler that can call both master and slave ISRs.
  1457. *
  1458. * The master and slave ISRs are called through function pointers in order to decouple
  1459. * this code from the ISR functions. Without this, the linker would always pull in both
  1460. * ISRs and every function they call, even if only the functional API was used.
  1461. *
  1462. * @param base The LPI2C peripheral base address.
  1463. * @param instance The LPI2C peripheral instance number.
  1464. */
  1465. static void LPI2C_CommonIRQHandler(LPI2C_Type *base, uint32_t instance)
  1466. {
  1467. /* Check for master IRQ. */
  1468. if ((base->MCR & LPI2C_MCR_MEN_MASK) && s_lpi2cMasterIsr)
  1469. {
  1470. /* Master mode. */
  1471. s_lpi2cMasterIsr(base, s_lpi2cMasterHandle[instance]);
  1472. }
  1473. /* Check for slave IRQ. */
  1474. if ((base->SCR & LPI2C_SCR_SEN_MASK) && s_lpi2cSlaveIsr)
  1475. {
  1476. /* Slave mode. */
  1477. s_lpi2cSlaveIsr(base, s_lpi2cSlaveHandle[instance]);
  1478. }
  1479. /* Add for ARM errata 838869, affects Cortex-M4, Cortex-M4F Store immediate overlapping
  1480. exception return operation might vector to incorrect interrupt */
  1481. #if defined __CORTEX_M && (__CORTEX_M == 4U)
  1482. __DSB();
  1483. #endif
  1484. }
  1485. #if defined(LPI2C0)
  1486. /* Implementation of LPI2C0 handler named in startup code. */
  1487. void LPI2C0_DriverIRQHandler(void)
  1488. {
  1489. LPI2C_CommonIRQHandler(LPI2C0, 0);
  1490. }
  1491. #endif
  1492. #if defined(LPI2C1)
  1493. /* Implementation of LPI2C1 handler named in startup code. */
  1494. void LPI2C1_DriverIRQHandler(void)
  1495. {
  1496. LPI2C_CommonIRQHandler(LPI2C1, 1);
  1497. }
  1498. #endif
  1499. #if defined(LPI2C2)
  1500. /* Implementation of LPI2C2 handler named in startup code. */
  1501. void LPI2C2_DriverIRQHandler(void)
  1502. {
  1503. LPI2C_CommonIRQHandler(LPI2C2, 2);
  1504. }
  1505. #endif
  1506. #if defined(LPI2C3)
  1507. /* Implementation of LPI2C3 handler named in startup code. */
  1508. void LPI2C3_DriverIRQHandler(void)
  1509. {
  1510. LPI2C_CommonIRQHandler(LPI2C3, 3);
  1511. }
  1512. #endif
  1513. #if defined(CM4_0__LPI2C)
  1514. /* Implementation of CM4_0__LPI2C handler named in startup code. */
  1515. void M4_0_LPI2C_DriverIRQHandler(void)
  1516. {
  1517. LPI2C_CommonIRQHandler(CM4_0__LPI2C, LPI2C_GetInstance(CM4_0__LPI2C));
  1518. }
  1519. #endif
  1520. #if defined(CM4_1__LPI2C)
  1521. /* Implementation of CM4_1__LPI2C handler named in startup code. */
  1522. void M4_1_LPI2C_DriverIRQHandler(void)
  1523. {
  1524. LPI2C_CommonIRQHandler(CM4_1__LPI2C, LPI2C_GetInstance(CM4_1__LPI2C));
  1525. }
  1526. #endif
  1527. #if defined(DMA__LPI2C0)
  1528. /* Implementation of DMA__LPI2C0 handler named in startup code. */
  1529. void DMA_I2C0_INT_DriverIRQHandler(void)
  1530. {
  1531. LPI2C_CommonIRQHandler(DMA__LPI2C0, LPI2C_GetInstance(DMA__LPI2C0));
  1532. }
  1533. #endif
  1534. #if defined(DMA__LPI2C1)
  1535. /* Implementation of DMA__LPI2C1 handler named in startup code. */
  1536. void DMA_I2C1_INT_DriverIRQHandler(void)
  1537. {
  1538. LPI2C_CommonIRQHandler(DMA__LPI2C1, LPI2C_GetInstance(DMA__LPI2C1));
  1539. }
  1540. #endif
  1541. #if defined(DMA__LPI2C2)
  1542. /* Implementation of DMA__LPI2C2 handler named in startup code. */
  1543. void DMA_I2C2_INT_DriverIRQHandler(void)
  1544. {
  1545. LPI2C_CommonIRQHandler(DMA__LPI2C2, LPI2C_GetInstance(DMA__LPI2C2));
  1546. }
  1547. #endif
  1548. #if defined(DMA__LPI2C3)
  1549. /* Implementation of DMA__LPI2C3 handler named in startup code. */
  1550. void DMA_I2C3_INT_DriverIRQHandler(void)
  1551. {
  1552. LPI2C_CommonIRQHandler(DMA__LPI2C3, LPI2C_GetInstance(DMA__LPI2C3));
  1553. }
  1554. #endif
  1555. #if defined(DMA__LPI2C4)
  1556. /* Implementation of DMA__LPI2C3 handler named in startup code. */
  1557. void DMA_I2C4_INT_DriverIRQHandler(void)
  1558. {
  1559. LPI2C_CommonIRQHandler(DMA__LPI2C4, LPI2C_GetInstance(DMA__LPI2C4));
  1560. }
  1561. #endif