hal_i2c_lld.c 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065
  1. /*
  2. ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. /*
  14. TODO:
  15. 1. Make sure slave mode registers updated OK
  16. 2. Test what of the newly inserted defines etc is actually necessary
  17. 3. Check whether all relevant features available on all ports on all processors (they are on F7, F051)
  18. 4. Do we need timer to get involved on master mode transactions? (May be multimaster requirement)
  19. 5. What about multimaster? Possibly nothing special to do, other than support all transitions round master and slave modes.
  20. (Manual: "By default, it operates in slave mode. The interface automatically switches from slave to
  21. master when it generates a START condition, and from master to slave if an arbitration loss
  22. or a STOP generation occurs, allowing multimaster capability")
  23. 6. Understand use of lock timer - may only be relevant for multimaster, or even unnecessary
  24. 7. Check slave transfers > 255 bytes
  25. NOTES:
  26. 1. 10-bit addressing, masking options not currently supported in software in slave mode
  27. (OAR1 hardware supports single 10-bit address matching; OAR2 supports 7-bit addressing with mask)
  28. 2. Address zero supported by setting 'General Call' flag in CR1 in slave mode (set with call to match address zero)
  29. 3. Clock stretching always enabled
  30. 4. Relevant configurable bits in CR1:
  31. ANFOFF (analog noise filter)
  32. DNF (digital noise filter bits)
  33. 5. Setting STM32_I2C_DEBUG_ENABLE to TRUE logs various events into a short circular buffer, which can then be examined using
  34. the debugger. Alternatively, a call to i2cPrintQ(BaseSequentialStream *chp) prints the buffer. Note that the buffer only
  35. has a write pointer, so once full its necessary to infer the start and end of the data
  36. */
  37. /**
  38. * @file STM32/I2Cv2/i2c_lld.c
  39. * @brief STM32 I2C subsystem low level driver source.
  40. *
  41. * @addtogroup I2C
  42. * @{
  43. */
  44. #include "hal.h"
  45. #if HAL_USE_I2C || defined(__DOXYGEN__)
  46. /*===========================================================================*/
  47. /* Driver local definitions. */
  48. /*===========================================================================*/
  49. #if STM32_I2C_USE_DMA == TRUE
  50. #define DMAMODE_COMMON \
  51. (STM32_DMA_CR_PSIZE_BYTE | STM32_DMA_CR_MSIZE_BYTE | \
  52. STM32_DMA_CR_MINC | STM32_DMA_CR_DMEIE | \
  53. STM32_DMA_CR_TEIE | STM32_DMA_CR_TCIE)
  54. #define I2C1_RX_DMA_CHANNEL \
  55. STM32_DMA_GETCHANNEL(STM32_I2C_I2C1_RX_DMA_STREAM, \
  56. STM32_I2C1_RX_DMA_CHN)
  57. #define I2C1_TX_DMA_CHANNEL \
  58. STM32_DMA_GETCHANNEL(STM32_I2C_I2C1_TX_DMA_STREAM, \
  59. STM32_I2C1_TX_DMA_CHN)
  60. #define I2C2_RX_DMA_CHANNEL \
  61. STM32_DMA_GETCHANNEL(STM32_I2C_I2C2_RX_DMA_STREAM, \
  62. STM32_I2C2_RX_DMA_CHN)
  63. #define I2C2_TX_DMA_CHANNEL \
  64. STM32_DMA_GETCHANNEL(STM32_I2C_I2C2_TX_DMA_STREAM, \
  65. STM32_I2C2_TX_DMA_CHN)
  66. #define I2C3_RX_DMA_CHANNEL \
  67. STM32_DMA_GETCHANNEL(STM32_I2C_I2C3_RX_DMA_STREAM, \
  68. STM32_I2C3_RX_DMA_CHN)
  69. #define I2C3_TX_DMA_CHANNEL \
  70. STM32_DMA_GETCHANNEL(STM32_I2C_I2C3_TX_DMA_STREAM, \
  71. STM32_I2C3_TX_DMA_CHN)
  72. #define I2C4_RX_DMA_CHANNEL \
  73. STM32_DMA_GETCHANNEL(STM32_I2C_I2C4_RX_DMA_STREAM, \
  74. STM32_I2C4_RX_DMA_CHN)
  75. #define I2C4_TX_DMA_CHANNEL \
  76. STM32_DMA_GETCHANNEL(STM32_I2C_I2C4_TX_DMA_STREAM, \
  77. STM32_I2C4_TX_DMA_CHN)
  78. #endif /* STM32_I2C_USE_DMA == TRUE */
  79. #if STM32_I2C_USE_DMA == TRUE
  80. #define i2c_lld_get_rxbytes(i2cp) dmaStreamGetTransactionSize((i2cp)->dmarx)
  81. #define i2c_lld_get_txbytes(i2cp) dmaStreamGetTransactionSize((i2cp)->dmatx)
  82. #else
  83. #define i2c_lld_get_rxbytes(i2cp) (i2cp)->rxbytes
  84. #define i2c_lld_get_txbytes(i2cp) (i2cp)->txbytes
  85. #endif
  86. /*===========================================================================*/
  87. /* Driver constants. */
  88. /*===========================================================================*/
  89. #define I2C_ERROR_MASK \
  90. ((uint32_t)(I2C_ISR_BERR | I2C_ISR_ARLO | I2C_ISR_OVR | I2C_ISR_PECERR | \
  91. I2C_ISR_TIMEOUT | I2C_ISR_ALERT))
  92. #define I2C_INT_MASK \
  93. ((uint32_t)(I2C_ISR_TCR | I2C_ISR_TC | I2C_ISR_STOPF | I2C_ISR_NACKF | \
  94. I2C_ISR_ADDR | I2C_ISR_RXNE | I2C_ISR_TXIS))
  95. /* Mask of interrupt bits cleared automatically - we mustn't clear ADDR else clock stretching doesn't happen */
  96. #define I2C_INT_CLEAR_MASK \
  97. ((uint32_t)(I2C_ISR_TCR | I2C_ISR_TC | I2C_ISR_STOPF | I2C_ISR_NACKF | \
  98. I2C_ISR_RXNE | I2C_ISR_TXIS))
  99. /*===========================================================================*/
  100. /* Driver exported variables. */
  101. /*===========================================================================*/
  102. /** @brief I2C1 driver identifier.*/
  103. #if STM32_I2C_USE_I2C1 || defined(__DOXYGEN__)
  104. I2CDriver I2CD1;
  105. #endif
  106. /** @brief I2C2 driver identifier.*/
  107. #if STM32_I2C_USE_I2C2 || defined(__DOXYGEN__)
  108. I2CDriver I2CD2;
  109. #endif
  110. /** @brief I2C3 driver identifier.*/
  111. #if STM32_I2C_USE_I2C3 || defined(__DOXYGEN__)
  112. I2CDriver I2CD3;
  113. #endif
  114. /** @brief I2C4 driver identifier.*/
  115. #if STM32_I2C_USE_I2C4 || defined(__DOXYGEN__)
  116. I2CDriver I2CD4;
  117. #endif
  118. /*===========================================================================*/
  119. /* Driver local variables and types. */
  120. /*===========================================================================*/
  121. #if STM32_I2C_DEBUG_ENABLE
  122. /*
  123. * Quick and dirty queue to record event interrupts (useful for debug)
  124. *
  125. * Assigned codes (may be others not noted here):
  126. * 0x02 - NAK received
  127. * 0x03 - transfer complete received
  128. * 0x04 - Address match (records current mode before any error recovery etc)
  129. * 0x05 - STOP received
  130. * 0x06 - Part transfer complete interrupt
  131. * 0x07 - Recovery from untidily finished previous transaction
  132. * 0x08 - Recovery from untidily finished previous transaction
  133. * 0x09 - Recovery from untidily finished previous transaction
  134. * 0x10 - error in slave address match - send
  135. * 0x11 - error in slave address match - receive
  136. * 0x12 - address match - send
  137. * 0x13 - address match - receive
  138. * 0x14 - start slave receive operation
  139. * 0x15 - lock on pending slave receive operation (no buffer)
  140. * 0x16 - start slave transmit operation
  141. * 0x17 - lock on pending slave transmit operation (no buffer available)
  142. * 0x80 - new reply set
  143. * 0x81 - reply used immediately
  144. * 0x82 - new receive buffer set
  145. * 0x83 - receive buffer used immediately
  146. * 0xcc - clearing down after transmission - triggered by NAK received (usually valid)
  147. * 0xd0 - Slave error being signalled
  148. * 0xd1 - Slave error due to timeout
  149. */
  150. #define QEVENTS 32
  151. typedef struct i2cQ_t {
  152. uint8_t code;
  153. uint8_t state; // Channel state
  154. uint8_t mode; // Mode (mostly for slave)
  155. uint16_t param; // Parameter sometimes used
  156. } i2cQ_t;
  157. i2cQ_t i2cQ[QEVENTS];
  158. unsigned i2cI = QEVENTS;
  159. #define qEvt(posn,info) {if (++i2cI >= QEVENTS) i2cI = 0; \
  160. i2cQ[i2cI].code=(posn); i2cQ[i2cI].state=(i2cp->state); i2cQ[i2cI].mode=(i2cp->mode); i2cQ[i2cI].param=(info); }
  161. #include "chprintf.h"
  162. void i2cPrintQ(BaseSequentialStream *chp)
  163. {
  164. uint8_t i;
  165. if (QEVENTS == 0)
  166. {
  167. chprintf(chp, "I2C Debug queue disabled\r\n");
  168. }
  169. else
  170. {
  171. chprintf(chp, "I2C debug ring - write pointer currently %02d\r\n", i2cI);
  172. }
  173. for (i = 0; i < QEVENTS; i++)
  174. {
  175. chprintf(chp, "%02d: %02x->%02x %02x %04x\r\n", i, i2cQ[i].code, i2cQ[i].state, i2cQ[i].mode, i2cQ[i].param);
  176. if (i2cQ[i].code == 0) break; // Handle partially filled queue
  177. }
  178. }
  179. #else
  180. #define qEvt(posn,info)
  181. #endif
  182. #if HAL_USE_I2C_SLAVE /* I2C slave mode support */
  183. void I2CSlaveDummyCB(I2CDriver *i2cp)
  184. /*
  185. dummy callback -- placeholder to ignore event
  186. */
  187. {(void)i2cp;}
  188. /* lock bus on receive or reply message */
  189. const I2CSlaveMsg I2CSlaveLockOnMsg = {
  190. 0, NULL, I2CSlaveDummyCB, I2CSlaveDummyCB, I2CSlaveDummyCB
  191. };
  192. #endif
  193. /*===========================================================================*/
  194. /* Driver local functions. */
  195. /*===========================================================================*/
  196. #if HAL_USE_I2C_MASTER
  197. /**
  198. * @brief Slave (remote) address setup in master mode.
  199. * @note The RW bit is set to zero internally.
  200. *
  201. * @param[in] i2cp pointer to the @p I2CDriver object
  202. * @param[in] addr slave device address
  203. *
  204. * @notapi
  205. */
  206. static void i2c_lld_set_address(I2CDriver *i2cp, i2caddr_t addr) {
  207. I2C_TypeDef *dp = i2cp->i2c;
  208. /* Address alignment depends on the addressing mode selected.*/
  209. if ((i2cp->config->cr2 & I2C_CR2_ADD10) == 0U)
  210. dp->CR2 = (uint32_t)addr << 1U;
  211. else
  212. dp->CR2 = (uint32_t)addr;
  213. }
  214. #endif
  215. /**
  216. * @brief I2C RX transfer setup.
  217. * @note Configures transfer count and related flags
  218. *
  219. * @param[in] i2cp pointer to the @p I2CDriver object
  220. *
  221. * @notapi
  222. */
  223. static void i2c_lld_setup_rx_transfer(I2CDriver *i2cp) {
  224. I2C_TypeDef *dp = i2cp->i2c;
  225. uint32_t reload;
  226. size_t n;
  227. /* The unit can transfer 255 bytes maximum in a single operation (device constraint). */
  228. #if STM32_I2C_USE_DMA
  229. if (i2cp->config->rxchar_cb)
  230. {
  231. n = i2cp->rxbytes; // Always interrupt-driven if we have a receive callback
  232. }
  233. else
  234. {
  235. n = i2c_lld_get_rxbytes(i2cp); // Otherwise get length from DMA or counter as appropriate
  236. }
  237. #else
  238. n = i2cp->rxbytes;
  239. #endif
  240. if (n > 255U) {
  241. n = 255U;
  242. reload = I2C_CR2_RELOAD;
  243. }
  244. else {
  245. reload = 0U;
  246. }
  247. /* Configures the CR2 registers with both the calculated and static
  248. settings. (Nothing much relevant in static settings - just PEC for SMBUS? */
  249. dp->CR2 = (dp->CR2 & ~(I2C_CR2_NBYTES | I2C_CR2_RELOAD)) | i2cp->config->cr2 | I2C_CR2_RD_WRN |
  250. (n << 16U) | reload;
  251. }
  252. /**
  253. * @brief I2C TX transfer setup.
  254. * @note Configures transfer count and related flags
  255. *
  256. * @param[in] i2cp pointer to the @p I2CDriver object
  257. *
  258. * @notapi
  259. */
  260. static void i2c_lld_setup_tx_transfer(I2CDriver *i2cp) {
  261. I2C_TypeDef *dp = i2cp->i2c;
  262. uint32_t reload;
  263. size_t n;
  264. /* The unit can transfer 255 bytes maximum in a single operation. */
  265. n = i2c_lld_get_txbytes(i2cp); // Get transaction size from DMA or buffer as configured
  266. if (n > 255U) {
  267. n = 255U;
  268. reload = I2C_CR2_RELOAD;
  269. }
  270. else {
  271. reload = 0U;
  272. }
  273. /* Configures the CR2 registers with both the calculated and static
  274. settings.*/
  275. dp->CR2 = (dp->CR2 & ~(I2C_CR2_NBYTES | I2C_CR2_RELOAD)) | i2cp->config->cr2 |
  276. (n << 16U) | reload;
  277. }
  278. /**
  279. * @brief Aborts an I2C transaction.
  280. *
  281. * @param[in] i2cp pointer to the @p I2CDriver object
  282. *
  283. * @notapi
  284. */
  285. static void i2c_lld_abort_operation(I2CDriver *i2cp) {
  286. I2C_TypeDef *dp = i2cp->i2c;
  287. // Note: clearing PE doesn't affect configuration bits (including slave addresses)
  288. if (dp->CR1 & I2C_CR1_PE) {
  289. /* Stops the I2C peripheral.*/
  290. dp->CR1 &= ~I2C_CR1_PE;
  291. while (dp->CR1 & I2C_CR1_PE)
  292. dp->CR1 &= ~I2C_CR1_PE;
  293. dp->CR1 |= I2C_CR1_PE;
  294. }
  295. #if STM32_I2C_USE_DMA == TRUE
  296. /* Stops the associated DMA streams.*/
  297. dmaStreamDisable(i2cp->dmatx);
  298. dmaStreamDisable(i2cp->dmarx);
  299. #else
  300. dp->CR1 &= ~(I2C_CR1_TXIE | I2C_CR1_RXIE); // Stop byte-orientated interrupts
  301. #endif
  302. }
  303. #if HAL_USE_I2C_SLAVE || HAL_USE_I2C_LOCK
  304. /**
  305. * @brief stop transaction timeout countdown
  306. *
  307. * @param[in] i2cp pointer to the @p I2CDriver object
  308. *
  309. * @notapi
  310. */
  311. static inline void stopTimer(I2CDriver *i2cp)
  312. {
  313. osalSysLockFromISR();
  314. chVTResetI(&i2cp->timer);
  315. osalSysUnlockFromISR();
  316. }
  317. #else
  318. #define stopTimer(ignored) {}
  319. #endif
  320. #if HAL_USE_I2C_SLAVE /* I2C slave mode support */
  321. /**
  322. * @brief report error via slave exception callback
  323. *
  324. * @param[in] i2cp pointer to the @p I2CDriver object
  325. *
  326. * @note moves back to the idle mode
  327. * @notapi
  328. */
  329. static inline void reportSlaveError(I2CDriver *i2cp) {
  330. if (i2cp->mode >= i2cIsMaster) return;
  331. qEvt(0xd0, i2cp->slaveErrors);
  332. const I2CSlaveMsg *xfer = i2cp->mode >= i2cSlaveReplying ?
  333. i2cp->slaveReply : i2cp->slaveRx;
  334. if (xfer->exception)
  335. xfer->exception(i2cp);
  336. i2cp->mode = i2cIdle;
  337. i2cp->targetAdr = i2cInvalidAdr;
  338. }
  339. /**
  340. * @brief Handling of stalled slave mode I2C transactions - timer handler.
  341. *
  342. * @param[in] i2cp pointer to the @p I2CDriver object
  343. *
  344. * @notapi
  345. */
  346. static void slaveTimeExpired(void *i2cv) {
  347. I2CDriver *i2cp = i2cv;
  348. if (i2cp->mode < i2cIsMaster)
  349. {
  350. i2c_lld_abort_operation(i2cp);
  351. reportSlaveError(i2cp);
  352. qEvt(0xd1, 0);
  353. }
  354. }
  355. /**
  356. * @brief start or restart slave mode transaction
  357. *
  358. * @param[in] i2cp pointer to the @p I2CDriver object
  359. * @param[in] targetAdr slave address which was matched
  360. *
  361. * @notapi
  362. */
  363. static inline void i2cStartSlaveAction(I2CDriver *i2cp, i2caddr_t targetAdr)
  364. {
  365. stopTimer(i2cp);
  366. i2cp->targetAdr = targetAdr;
  367. i2cp->slaveBytes = 0;
  368. i2cp->slaveErrors = 0;
  369. if (i2cp->slaveTimeout != TIME_INFINITE)
  370. {
  371. osalSysLockFromISR();
  372. chVTSetI(&i2cp->timer, i2cp->slaveTimeout, slaveTimeExpired, i2cp);
  373. osalSysUnlockFromISR();
  374. }
  375. }
  376. /**
  377. * @brief end slave receive message DMA
  378. *
  379. * @param[in] i2cp pointer to the @p I2CDriver object
  380. *
  381. * @notapi
  382. */
  383. static inline void i2cEndSlaveRxDMA(I2CDriver *i2cp)
  384. {
  385. size_t bytesRemaining = i2c_lld_get_rxbytes(i2cp);
  386. if (i2cp->slaveBytes)
  387. i2cp->slaveBytes += 0xffff - bytesRemaining;
  388. else
  389. i2cp->slaveBytes = i2cp->slaveRx->size - bytesRemaining;
  390. #if STM32_I2C_USE_DMA == TRUE
  391. /* Disabling RX DMA channel.*/
  392. dmaStreamDisable(i2cp->dmarx);
  393. #else
  394. i2cp->i2c->CR1 &= ~(I2C_CR1_RXIE);
  395. #endif
  396. }
  397. /**
  398. * @brief end slave transmit DMA
  399. *
  400. * @param[in] i2cp pointer to the @p I2CDriver object
  401. * @param[in] bytesRemaining bytes lost in output queue
  402. *
  403. * @notapi
  404. */
  405. static inline void i2cEndSlaveTxDMA(I2CDriver *i2cp, size_t bytesRemaining)
  406. {
  407. bytesRemaining += i2c_lld_get_rxbytes(i2cp);
  408. if (i2cp->slaveBytes)
  409. i2cp->slaveBytes += 0xffff - bytesRemaining;
  410. else
  411. i2cp->slaveBytes = i2cp->slaveReply->size - bytesRemaining;
  412. #if STM32_I2C_USE_DMA == TRUE
  413. /* Disabling TX DMA channel.*/
  414. dmaStreamDisable(i2cp->dmatx);
  415. #else
  416. i2cp->i2c->CR1 &= ~(I2C_CR1_TXIE);
  417. #endif
  418. }
  419. #endif
  420. /**
  421. * @brief Start a receive transaction (by enabling DMA, or enabling Rx character interrupts)
  422. *
  423. * @note All registers etc must be set up first
  424. */
  425. static inline void i2cStartReceive(I2CDriver *i2cp)
  426. {
  427. #if STM32_I2C_USE_DMA == TRUE
  428. if (i2cp->config->rxchar_cb)
  429. {
  430. // Callback in use - use interrupt-driven transfer
  431. i2cp->i2c->CR1 |= I2C_CR1_TCIE | I2C_CR1_RXIE;
  432. }
  433. else
  434. {
  435. /* Enabling RX DMA.*/
  436. dmaStreamEnable(i2cp->dmarx);
  437. /* Transfer complete interrupt enabled.*/
  438. i2cp->i2c->CR1 |= I2C_CR1_TCIE;
  439. }
  440. #else
  441. /* Transfer complete and RX interrupts enabled.*/
  442. i2cp->i2c->CR1 |= I2C_CR1_TCIE | I2C_CR1_RXIE;
  443. #endif
  444. }
  445. /**
  446. * @brief Disable transmit data transfer, whether DMA or interrupt-driven
  447. */
  448. static inline void i2cDisableTransmitOperation(I2CDriver *i2cp)
  449. {
  450. #if STM32_I2C_USE_DMA == TRUE
  451. /* Disabling TX DMA channel.*/
  452. dmaStreamDisable(i2cp->dmatx);
  453. #else
  454. i2cp->i2c->CR1 &= ~(I2C_CR1_TXIE);
  455. #endif
  456. }
  457. /**
  458. * @brief Disable receive data transfer, whether DMA or interrupt-driven
  459. */
  460. static inline void i2cDisableReceiveOperation(I2CDriver *i2cp)
  461. {
  462. #if STM32_I2C_USE_DMA == TRUE
  463. /* Disabling RX DMA channel.*/
  464. dmaStreamDisable(i2cp->dmarx);
  465. #else
  466. i2cp->i2c->CR1 &= ~(I2C_CR1_RXIE);
  467. #endif
  468. }
  469. /*===========================================================================*/
  470. /* Shared ISR Code */
  471. /*===========================================================================*/
  472. /**
  473. * @brief I2C shared ISR code - 'Normal' (non-error) interrupts.
  474. *
  475. * @param[in] i2cp pointer to the @p I2CDriver object
  476. * @param[in] isr content of the ISR register to be decoded (no masking applied)
  477. *
  478. * @notapi
  479. */
  480. static void i2c_lld_serve_interrupt(I2CDriver *i2cp, uint32_t isr) {
  481. I2C_TypeDef *dp = i2cp->i2c;
  482. /* Check for received NACK, the transfer is aborted. Do this in all modes */
  483. if ((isr & I2C_ISR_NACKF) != 0U)
  484. {
  485. qEvt(2, 0);
  486. i2cDisableReceiveOperation(i2cp);
  487. i2cDisableTransmitOperation(i2cp);
  488. #if HAL_USE_I2C_SLAVE
  489. /* NACK of last byte transmitted in slave response is NORMAL -- not an error! */
  490. if (i2cp->mode == i2cSlaveReplying)
  491. {
  492. qEvt(0xcc,0);
  493. i2cEndSlaveTxDMA(i2cp, 1);
  494. if (i2cp->slaveReply->processMsg)
  495. i2cp->slaveReply->processMsg(i2cp);
  496. i2cp->targetAdr = i2cInvalidAdr;
  497. stopTimer(i2cp);
  498. return;
  499. }
  500. #endif
  501. /* Error flag.*/
  502. i2cp->errors |= I2C_ACK_FAILURE;
  503. /* Transaction finished, send the STOP. */
  504. dp->CR2 |= I2C_CR2_STOP;
  505. /* Make sure no more interrupts.*/
  506. dp->CR1 &= ~(I2C_CR1_TCIE | I2C_CR1_TXIE | I2C_CR1_RXIE | I2C_CR1_STOPIE);
  507. if (i2cp->mode < i2cIsMaster)
  508. {
  509. i2cp->mode = i2cIdle;
  510. }
  511. else
  512. {
  513. /* Master mode - Errors are signalled to the upper layer.*/
  514. i2cp->mode = i2cIdle;
  515. // Must only wake up thread in master mode.
  516. _i2c_wakeup_isr(i2cp); // This is a normal completion
  517. }
  518. return;
  519. }
  520. #if STM32_I2C_USE_DMA == FALSE
  521. /* Handling of data transfer if the DMA mode is disabled - done character by character. Mode should be irrelevant */
  522. {
  523. uint32_t cr1 = dp->CR1;
  524. if ((i2cp->state == I2C_ACTIVE_TX) || (i2cp->mode == i2cSlaveReplying))
  525. {
  526. /* Transmission phase.*/
  527. if (((cr1 &I2C_CR1_TXIE) != 0U) && ((isr & I2C_ISR_TXIS) != 0U)) {
  528. dp->TXDR = (uint32_t)*i2cp->txptr;
  529. i2cp->txptr++;
  530. i2cp->txbytes--;
  531. if (i2cp->txbytes == 0U) {
  532. dp->CR1 &= ~I2C_CR1_TXIE; // Last byte sent - stop Tx interrupt
  533. }
  534. }
  535. }
  536. else
  537. {
  538. /* Receive phase.*/
  539. if (((cr1 & I2C_CR1_RXIE) != 0U) && ((isr & I2C_ISR_RXNE) != 0U)) {
  540. uint8_t c;
  541. *i2cp->rxptr = c = (uint8_t)dp->RXDR;
  542. i2cp->rxptr++;
  543. i2cp->rxbytes--;
  544. if (i2cp->config->rxchar_cb)
  545. {
  546. if (i2cp->config->rxchar_cb(i2cp, c) > 0)
  547. {
  548. /* Transaction finished, send the STOP. */
  549. dp->CR2 |= I2C_CR2_STOP;
  550. /* Make sure no more interrupts.*/
  551. dp->CR1 &= ~(I2C_CR1_TCIE | I2C_CR1_TXIE | I2C_CR1_RXIE | I2C_CR1_STOPIE);
  552. if (i2cp->mode < i2cIsMaster)
  553. {
  554. i2cp->mode = i2cIdle;
  555. }
  556. else
  557. {
  558. /* Master mode - Errors are signalled to the upper layer.*/
  559. i2cp->mode = i2cIdle;
  560. // Must only wake up thread in master mode.
  561. _i2c_wakeup_isr(i2cp); // This is a normal completion
  562. }
  563. return;
  564. }
  565. }
  566. if (i2cp->rxbytes == 0U) {
  567. dp->CR1 &= ~I2C_CR1_RXIE; // Buffer full - stop reception (TODO: Should we send NAK?? Only possible in slave mode)
  568. }
  569. }
  570. }
  571. }
  572. #else
  573. /* Receive character phase with callback enabled. */
  574. if ((i2cp->state == I2C_ACTIVE_RX) || (i2cp->mode == i2cMasterRxing))
  575. {
  576. uint32_t cr1 = dp->CR1;
  577. if (((cr1 & I2C_CR1_RXIE) != 0U) && ((isr & I2C_ISR_RXNE) != 0U)) {
  578. uint8_t c;
  579. c = (uint8_t)dp->RXDR;
  580. *i2cp->rxptr = c;
  581. i2cp->rxptr++;
  582. i2cp->rxbytes--;
  583. if (i2cp->config->rxchar_cb)
  584. {
  585. if (i2cp->config->rxchar_cb(i2cp, c) > 0)
  586. {
  587. /* Transaction finished, send the STOP. */
  588. dp->CR2 |= I2C_CR2_STOP;
  589. /* Make sure no more interrupts.*/
  590. dp->CR1 &= ~(I2C_CR1_TCIE | I2C_CR1_TXIE | I2C_CR1_RXIE | I2C_CR1_STOPIE);
  591. if (i2cp->mode < i2cIsMaster)
  592. {
  593. i2cp->mode = i2cIdle;
  594. }
  595. else
  596. {
  597. /* Master mode - Errors are signalled to the upper layer.*/
  598. i2cp->mode = i2cIdle;
  599. // Must only wake up thread in master mode.
  600. _i2c_wakeup_isr(i2cp); // This is a normal completion
  601. }
  602. return;
  603. }
  604. }
  605. if (i2cp->rxbytes == 0U) {
  606. dp->CR1 &= ~I2C_CR1_RXIE; // Buffer full - stop reception (TODO: Should we send NAK?? Only possible in slave mode)
  607. }
  608. }
  609. }
  610. #endif
  611. /* Partial transfer handling, restarting the transfer and returning. */
  612. if ((isr & I2C_ISR_TCR) != 0U)
  613. {
  614. qEvt(0x06, 0);
  615. if ((i2cp->state == I2C_ACTIVE_TX) || (i2cp->mode == i2cSlaveReplying)) {
  616. i2c_lld_setup_tx_transfer(i2cp);
  617. }
  618. if ((i2cp->state == I2C_ACTIVE_RX) || (i2cp->mode == i2cSlaveRxing)) {
  619. i2c_lld_setup_rx_transfer(i2cp);
  620. }
  621. return;
  622. }
  623. /* The following condition is true if a transfer phase has been completed. */
  624. if ((isr & I2C_ISR_TC) != 0U)
  625. {
  626. qEvt(3,i2cp->state);
  627. #if HAL_USE_I2C_SLAVE
  628. switch (i2cp->mode)
  629. {
  630. case i2cLockedRxing : /* stretching clock before receiving message - Rx buffer might be full */
  631. case i2cLockedReplying :
  632. break; // TODO: Two unsupported cases to consider - maybe they can't happen
  633. case i2cSlaveReplying : // Must have just finished sending a reply in slave mode
  634. break; // Just go on to send STOP bit and tidy up
  635. case i2cSlaveRxing : // Must have just received a message - process if we can
  636. i2cEndSlaveRxDMA(i2cp);
  637. qEvt(0x20, 0);
  638. if (i2cp->slaveRx->processMsg)
  639. i2cp->slaveRx->processMsg(i2cp);
  640. // TODO: Should get a reply message set - if so, start to send it and return
  641. return; // For now, see what happens if we just return
  642. break;
  643. default : // Assume a master mode
  644. #endif
  645. if (i2cp->state == I2C_ACTIVE_TX) {
  646. /* End of the transmit phase.*/
  647. i2cDisableTransmitOperation(i2cp); // Disable
  648. /* Starting receive phase if necessary.*/
  649. if (i2c_lld_get_rxbytes(i2cp) > 0U) {
  650. /* Setting up the peripheral.*/
  651. i2c_lld_setup_rx_transfer(i2cp);
  652. #if STM32_I2C_USE_DMA == TRUE
  653. // If receive callback enabled, always transfer using interrupts
  654. if (i2cp->config->rxchar_cb)
  655. {
  656. /* RX interrupt enabled.*/
  657. dp->CR1 |= I2C_CR1_RXIE;
  658. }
  659. else
  660. {
  661. /* Enabling RX DMA.*/
  662. dmaStreamEnable(i2cp->dmarx);
  663. }
  664. #else
  665. /* RX interrupt enabled.*/
  666. dp->CR1 |= I2C_CR1_RXIE;
  667. #endif
  668. /* Starts the read operation.*/
  669. dp->CR2 |= I2C_CR2_START;
  670. /* State change.*/
  671. i2cp->state = I2C_ACTIVE_RX;
  672. i2cp->mode = i2cMasterRxing;
  673. /* Note, returning because the transaction is not over yet.*/
  674. return;
  675. }
  676. }
  677. else
  678. {
  679. /* End of the receive phase.*/
  680. i2cDisableReceiveOperation(i2cp);
  681. }
  682. #if HAL_USE_I2C_SLAVE
  683. }
  684. #endif
  685. /* Transaction finished sending the STOP. */
  686. dp->CR2 |= I2C_CR2_STOP;
  687. /* Make sure no more 'Transfer Complete' interrupts. */
  688. dp->CR1 &= ~I2C_CR1_TCIE;
  689. /* Normal transaction end.*/
  690. if (i2cp->mode < i2cIsMaster)
  691. {
  692. // Slave mode - just move to idle state
  693. i2cp->mode = i2cIdle;
  694. }
  695. else
  696. {
  697. i2cp->mode = i2cIdle;
  698. // Must only wake up thread in master mode
  699. _i2c_wakeup_isr(i2cp);
  700. }
  701. }
  702. #if HAL_USE_I2C_SLAVE
  703. uint8_t abort = 0;
  704. /* Check for address match - if so, we're slave */
  705. if ((isr & I2C_ISR_ADDR) != 0U)
  706. {
  707. i2caddr_t targetAdr = (isr & I2C_ISR_ADDCODE) >> 17; // Identify which slave address used
  708. uint8_t xferDir = (isr & I2C_ISR_DIR) ? 0 : 1; // Status bit is 0 for receive, 1 for transmit. xferDir inverts sense
  709. dp->CR1 |= I2C_CR1_STOPIE; // Enable STOP interrupt so we know when slave transaction done
  710. /* First, tidy up from previous transactions as necessary */
  711. qEvt(0x04, 0);
  712. switch (i2cp->mode) {
  713. case i2cIdle:
  714. break;
  715. case i2cSlaveRxing: /* Previous transaction not completed properly, or
  716. maybe we were sent a message without being asked for a reply */
  717. qEvt(0x07, 0);
  718. i2cEndSlaveRxDMA(i2cp);
  719. if (i2cp->slaveRx->processMsg)
  720. i2cp->slaveRx->processMsg(i2cp); // Execute callback if defined
  721. break;
  722. case i2cSlaveReplying: /* Master did not NACK last transmitted byte (most likely picked up by NAK handler) */
  723. qEvt(0x08, 0);
  724. if (!xferDir)
  725. {
  726. qEvt(0x09, 0);
  727. i2cEndSlaveTxDMA(i2cp, 2);
  728. if (i2cp->slaveReply->processMsg)
  729. i2cp->slaveReply->processMsg(i2cp);
  730. break;
  731. }
  732. // Intentionally don't break if we're addressed to receive
  733. default:
  734. // todo: Does this lot happen in the right order? Is an abort appropriate? Or should we just continue?
  735. qEvt(0x10 + xferDir, 0);
  736. i2cp->slaveErrors = I2C_UNKNOWN_ERROR + i2cp->mode;
  737. i2c_lld_abort_operation(i2cp); /* reset and reinit */
  738. stopTimer(i2cp);
  739. reportSlaveError(i2cp); // This clears down to idle
  740. abort = 1;
  741. }
  742. if (!abort)
  743. {
  744. qEvt(0x12 + xferDir, (i2cp->slaveNextRx->size));
  745. if (xferDir)
  746. {
  747. /* Start Receive */
  748. /* If receive buffer still full, need to extend clock for timeout. Otherwise set up to receive */
  749. dp->CR1 &= ~I2C_CR1_SBC; // Not needed with receive
  750. i2cStartSlaveAction(i2cp, targetAdr);
  751. const I2CSlaveMsg *rx = i2cp->slaveNextRx;
  752. if (rx->adrMatched) // Q: Can rx ever be NULL?
  753. rx->adrMatched(i2cp); // Execute callback on address match if specified
  754. rx = i2cp->slaveRx = i2cp->slaveNextRx; // Reload message pointer in case callback changed it
  755. if (rx->body && rx->size)
  756. {
  757. /* Receive buffer available - can receive immediately. Set up slave RX DMA */
  758. i2c_lld_setup_rx_transfer(i2cp);
  759. #if STM32_I2C_USE_DMA == TRUE
  760. /* RX DMA setup.*/
  761. dmaStreamSetMode(i2cp->dmarx, i2cp->rxdmamode);
  762. dmaStreamSetMemory0(i2cp->dmarx, rx->body);
  763. dmaStreamSetTransactionSize(i2cp->dmarx, rx->size);
  764. #else
  765. i2cp->rxptr = rx->body;
  766. i2cp->rxbytes = rx->size;
  767. #endif
  768. i2cStartReceive(i2cp);
  769. dp->ICR = I2C_ISR_ADDR; // We can release the clock stretch now
  770. i2cp->mode = i2cSlaveRxing;
  771. qEvt(0x14,0);
  772. }
  773. else
  774. {
  775. /* No reply set up - hold clock low and wait (happens automatically) */
  776. qEvt(0x15,0);
  777. i2cp->mode = i2cLockedRxing;
  778. }
  779. }
  780. else
  781. {
  782. /* Start Transmit */
  783. i2cStartSlaveAction(i2cp, targetAdr);
  784. const I2CSlaveMsg *reply = i2cp->slaveNextReply;
  785. const I2CSlaveMsg *rx = i2cp->slaveNextRx; // Receive control block
  786. if (rx->adrMatched) // Q: Can rx ever be NULL?
  787. rx->adrMatched(i2cp); // Execute callback on address match if specified
  788. reply = i2cp->slaveReply = i2cp->slaveNextReply; // Reload message pointer in case callback changed it
  789. if (reply->body && reply->size)
  790. {
  791. /* Reply message available - can send immediately. Set up slave TX DMA */
  792. #if STM32_I2C_USE_DMA == TRUE
  793. dmaStreamSetMode(i2cp->dmatx, i2cp->txdmamode);
  794. dmaStreamSetMemory0(i2cp->dmatx, reply->body);
  795. dmaStreamSetTransactionSize(i2cp->dmatx, reply->size);
  796. /* Start transmission */
  797. i2c_lld_setup_tx_transfer(i2cp);
  798. /* Enabling TX DMA.*/
  799. dmaStreamEnable(i2cp->dmatx);
  800. /* Transfer complete interrupt enabled.*/
  801. dp->CR1 |= I2C_CR1_TCIE;
  802. #else
  803. /* Start transmission */
  804. i2cp->txptr = reply->body;
  805. i2cp->txbytes = reply->size;
  806. i2c_lld_setup_tx_transfer(i2cp);
  807. /* Transfer complete and TX character interrupts enabled.*/
  808. dp->CR1 |= I2C_CR1_TCIE | I2C_CR1_TXIE;
  809. #endif
  810. qEvt(0x16,0);
  811. i2cp->mode = i2cSlaveReplying;
  812. dp->CR1 |= I2C_CR1_SBC; // Need this to enable byte counter in transmit mode
  813. dp->ICR = I2C_ISR_ADDR; // We can release the clock stretch now
  814. }
  815. else
  816. {
  817. // clock is automatically stretched if we don't clear the status bit
  818. //dp->CR2 &= (uint16_t)(~I2C_CR2_ITEVTEN);
  819. qEvt(0x17, 0);
  820. i2cp->mode = i2cLockedReplying;
  821. }
  822. }
  823. } /* if !abort */
  824. }
  825. if ((isr & I2C_ISR_STOPF) != 0U) {
  826. /*
  827. * STOP received:
  828. * in master mode, if generated by peripheral - can probably just ignore
  829. * in slave mode, if detected on bus (from any source?)
  830. *
  831. * Clear everything down - particularly relevant in slave mode
  832. */
  833. qEvt(0x05, 0);
  834. dp->CR1 &= ~I2C_CR1_STOPIE; // Disable STOP interrupt
  835. i2cDisableReceiveOperation(i2cp); // These two may not be necessary
  836. i2cDisableTransmitOperation(i2cp);
  837. stopTimer(i2cp);
  838. i2cp->mode = i2cIdle;
  839. }
  840. #endif
  841. }
  842. /**
  843. * @brief I2C error handler.
  844. *
  845. * @param[in] i2cp pointer to the @p I2CDriver object
  846. * @param[in] isr content of the ISR register to be decoded (no masking applied)
  847. *
  848. * @notapi
  849. */
  850. static void i2c_lld_serve_error_interrupt(I2CDriver *i2cp, uint32_t isr) {
  851. i2cDisableReceiveOperation(i2cp);
  852. i2cDisableTransmitOperation(i2cp);
  853. stopTimer(i2cp);
  854. #if HAL_USE_I2C_SLAVE
  855. // In slave mode, just clock errors and return
  856. if (i2cp->mode < i2cIsMaster)
  857. {
  858. reportSlaveError(i2cp); // This clears down to idle
  859. return;
  860. }
  861. #endif
  862. if (isr & I2C_ISR_BERR)
  863. i2cp->errors |= I2C_BUS_ERROR;
  864. if (isr & I2C_ISR_ARLO)
  865. i2cp->errors |= I2C_ARBITRATION_LOST;
  866. if (isr & I2C_ISR_OVR)
  867. i2cp->errors |= I2C_OVERRUN;
  868. if (isr & I2C_ISR_TIMEOUT)
  869. i2cp->errors |= I2C_TIMEOUT;
  870. /* If some error has been identified then wake up the waiting thread.*/
  871. if (i2cp->errors != I2C_NO_ERROR)
  872. {
  873. i2cp->mode = i2cIdle;
  874. _i2c_wakeup_error_isr(i2cp);
  875. }
  876. }
  877. #if HAL_USE_I2C_LOCK /* I2C bus locking support */
  878. /**
  879. * @brief Handling of expired master bus lock timer
  880. *
  881. * @param[in] i2cv pointer to the @p I2CDriver object
  882. *
  883. * @notapi
  884. */
  885. static void lockExpired(void *i2cv) {
  886. I2CDriver *i2cp = i2cv;
  887. if (i2cp->mode == i2cIsMaster && !i2cp->thread) { /* between transactions */
  888. i2cp->i2c->CR2 |= I2C_CR2_STOP;
  889. i2cp->mode = i2cIdle;
  890. }
  891. i2cp->lockDuration = TIME_IMMEDIATE;
  892. }
  893. /**
  894. * @brief Lock I2C bus at the beginning of the next message
  895. *
  896. * @param[in] i2cp pointer to the @p I2CDriver object
  897. * @param[in] lockDuration max number of ticks to hold bus locked
  898. * - @a TIME_INFINITE no timeout.
  899. * - @a TIME_IMMEDIATE unlock the bus immediately
  900. * .
  901. *
  902. * Lock I2C bus at the beginning of the next message sent
  903. * for a maximum of lockDuration ticks. No other I2C masters will
  904. * be allowed to interrupt until i2cUnlock() is called.
  905. *
  906. * @notapi
  907. **/
  908. void i2c_lld_lock(I2CDriver *i2cp, systime_t lockDuration)
  909. {
  910. i2cp->lockDuration = lockDuration;
  911. if (i2cp->mode >= i2cIsMaster) {
  912. stopTimer(i2cp);
  913. if (lockDuration == TIME_IMMEDIATE)
  914. lockExpired(i2cp);
  915. else if (lockDuration != TIME_INFINITE)
  916. chVTSetI(&i2cp->timer, lockDuration, lockExpired, i2cp);
  917. }
  918. }
  919. #endif
  920. /*===========================================================================*/
  921. /* Driver interrupt handlers. */
  922. /*===========================================================================*/
  923. #if STM32_I2C_USE_I2C1 || defined(__DOXYGEN__)
  924. #if defined(STM32_I2C1_GLOBAL_HANDLER) || defined(__DOXYGEN__)
  925. /**
  926. * @brief I2C1 event interrupt handler.
  927. *
  928. * @notapi
  929. */
  930. OSAL_IRQ_HANDLER(STM32_I2C1_GLOBAL_HANDLER) {
  931. uint32_t isr = I2CD1.i2c->ISR;
  932. OSAL_IRQ_PROLOGUE();
  933. /* Clearing IRQ bits.*/
  934. I2CD1.i2c->ICR = isr & ~I2C_ISR_ADDR;
  935. if (isr & I2C_ERROR_MASK)
  936. i2c_lld_serve_error_interrupt(&I2CD1, isr);
  937. else if (isr & I2C_INT_MASK)
  938. i2c_lld_serve_interrupt(&I2CD1, isr);
  939. OSAL_IRQ_EPILOGUE();
  940. }
  941. #elif defined(STM32_I2C1_EVENT_HANDLER) && defined(STM32_I2C1_ERROR_HANDLER)
  942. OSAL_IRQ_HANDLER(STM32_I2C1_EVENT_HANDLER) {
  943. uint32_t isr = I2CD1.i2c->ISR;
  944. OSAL_IRQ_PROLOGUE();
  945. /* Clearing IRQ bits.*/
  946. I2CD1.i2c->ICR = isr & I2C_INT_CLEAR_MASK;
  947. i2c_lld_serve_interrupt(&I2CD1, isr);
  948. OSAL_IRQ_EPILOGUE();
  949. }
  950. OSAL_IRQ_HANDLER(STM32_I2C1_ERROR_HANDLER) {
  951. uint32_t isr = I2CD1.i2c->ISR;
  952. OSAL_IRQ_PROLOGUE();
  953. /* Clearing IRQ bits.*/
  954. I2CD1.i2c->ICR = isr & I2C_ERROR_MASK;
  955. i2c_lld_serve_error_interrupt(&I2CD1, isr);
  956. OSAL_IRQ_EPILOGUE();
  957. }
  958. #else
  959. #error "I2C1 interrupt handlers not defined"
  960. #endif
  961. #endif /* STM32_I2C_USE_I2C1 */
  962. #if STM32_I2C_USE_I2C2 || defined(__DOXYGEN__)
  963. #if defined(STM32_I2C2_GLOBAL_HANDLER) || defined(__DOXYGEN__)
  964. /**
  965. * @brief I2C2 event interrupt handler.
  966. *
  967. * @notapi
  968. */
  969. OSAL_IRQ_HANDLER(STM32_I2C2_GLOBAL_HANDLER) {
  970. uint32_t isr = I2CD2.i2c->ISR;
  971. OSAL_IRQ_PROLOGUE();
  972. /* Clearing IRQ bits.*/
  973. I2CD2.i2c->ICR = isr & ~I2C_ISR_ADDR;
  974. if (isr & I2C_ERROR_MASK)
  975. i2c_lld_serve_error_interrupt(&I2CD2, isr);
  976. else if (isr & I2C_INT_MASK)
  977. i2c_lld_serve_interrupt(&I2CD2, isr);
  978. OSAL_IRQ_EPILOGUE();
  979. }
  980. #elif defined(STM32_I2C2_EVENT_HANDLER) && defined(STM32_I2C2_ERROR_HANDLER)
  981. OSAL_IRQ_HANDLER(STM32_I2C2_EVENT_HANDLER) {
  982. uint32_t isr = I2CD2.i2c->ISR;
  983. OSAL_IRQ_PROLOGUE();
  984. /* Clearing IRQ bits.*/
  985. I2CD2.i2c->ICR = isr & I2C_INT_CLEAR_MASK;
  986. i2c_lld_serve_interrupt(&I2CD2, isr);
  987. OSAL_IRQ_EPILOGUE();
  988. }
  989. OSAL_IRQ_HANDLER(STM32_I2C2_ERROR_HANDLER) {
  990. uint32_t isr = I2CD2.i2c->ISR;
  991. OSAL_IRQ_PROLOGUE();
  992. /* Clearing IRQ bits.*/
  993. I2CD2.i2c->ICR = isr & I2C_ERROR_MASK;
  994. i2c_lld_serve_error_interrupt(&I2CD2, isr);
  995. OSAL_IRQ_EPILOGUE();
  996. }
  997. #else
  998. #error "I2C2 interrupt handlers not defined"
  999. #endif
  1000. #endif /* STM32_I2C_USE_I2C2 */
  1001. #if STM32_I2C_USE_I2C3 || defined(__DOXYGEN__)
  1002. #if defined(STM32_I2C3_GLOBAL_HANDLER) || defined(__DOXYGEN__)
  1003. /**
  1004. * @brief I2C3 event interrupt handler.
  1005. *
  1006. * @notapi
  1007. */
  1008. OSAL_IRQ_HANDLER(STM32_I2C3_GLOBAL_HANDLER) {
  1009. uint32_t isr = I2CD3.i2c->ISR;
  1010. OSAL_IRQ_PROLOGUE();
  1011. /* Clearing IRQ bits.*/
  1012. I2CD3.i2c->ICR = isr & ~I2C_ISR_ADDR;
  1013. if (isr & I2C_ERROR_MASK)
  1014. i2c_lld_serve_error_interrupt(&I2CD3, isr);
  1015. else if (isr & I2C_INT_MASK)
  1016. i2c_lld_serve_interrupt(&I2CD3, isr);
  1017. OSAL_IRQ_EPILOGUE();
  1018. }
  1019. #elif defined(STM32_I2C3_EVENT_HANDLER) && defined(STM32_I2C3_ERROR_HANDLER)
  1020. OSAL_IRQ_HANDLER(STM32_I2C3_EVENT_HANDLER) {
  1021. uint32_t isr = I2CD3.i2c->ISR;
  1022. OSAL_IRQ_PROLOGUE();
  1023. /* Clearing IRQ bits.*/
  1024. I2CD3.i2c->ICR = isr & I2C_INT_CLEAR_MASK;
  1025. i2c_lld_serve_interrupt(&I2CD3, isr);
  1026. OSAL_IRQ_EPILOGUE();
  1027. }
  1028. OSAL_IRQ_HANDLER(STM32_I2C3_ERROR_HANDLER) {
  1029. uint32_t isr = I2CD3.i2c->ISR;
  1030. OSAL_IRQ_PROLOGUE();
  1031. /* Clearing IRQ bits.*/
  1032. I2CD3.i2c->ICR = isr & I2C_ERROR_MASK;
  1033. i2c_lld_serve_error_interrupt(&I2CD3, isr);
  1034. OSAL_IRQ_EPILOGUE();
  1035. }
  1036. #else
  1037. #error "I2C3 interrupt handlers not defined"
  1038. #endif
  1039. #endif /* STM32_I2C_USE_I2C3 */
  1040. #if STM32_I2C_USE_I2C4 || defined(__DOXYGEN__)
  1041. #if defined(STM32_I2C4_GLOBAL_HANDLER) || defined(__DOXYGEN__)
  1042. /**
  1043. * @brief I2C4 event interrupt handler.
  1044. *
  1045. * @notapi
  1046. */
  1047. OSAL_IRQ_HANDLER(STM32_I2C4_GLOBAL_HANDLER) {
  1048. uint32_t isr = I2CD4.i2c->ISR;
  1049. OSAL_IRQ_PROLOGUE();
  1050. /* Clearing IRQ bits.*/
  1051. I2CD4.i2c->ICR = isr & ~I2C_ISR_ADDR;
  1052. if (isr & I2C_ERROR_MASK)
  1053. i2c_lld_serve_error_interrupt(&I2CD4, isr);
  1054. else if (isr & I2C_INT_MASK)
  1055. i2c_lld_serve_interrupt(&I2CD4, isr);
  1056. OSAL_IRQ_EPILOGUE();
  1057. }
  1058. #elif defined(STM32_I2C4_EVENT_HANDLER) && defined(STM32_I2C4_ERROR_HANDLER)
  1059. OSAL_IRQ_HANDLER(STM32_I2C4_EVENT_HANDLER) {
  1060. uint32_t isr = I2CD4.i2c->ISR;
  1061. OSAL_IRQ_PROLOGUE();
  1062. /* Clearing IRQ bits.*/
  1063. I2CD4.i2c->ICR = isr & I2C_INT_CLEAR_MASK;
  1064. i2c_lld_serve_interrupt(&I2CD4, isr);
  1065. OSAL_IRQ_EPILOGUE();
  1066. }
  1067. OSAL_IRQ_HANDLER(STM32_I2C4_ERROR_HANDLER) {
  1068. uint32_t isr = I2CD4.i2c->ISR;
  1069. OSAL_IRQ_PROLOGUE();
  1070. /* Clearing IRQ bits.*/
  1071. I2CD4.i2c->ICR = isr & I2C_ERROR_MASK;
  1072. i2c_lld_serve_error_interrupt(&I2CD4, isr);
  1073. OSAL_IRQ_EPILOGUE();
  1074. }
  1075. #else
  1076. #error "I2C4 interrupt handlers not defined"
  1077. #endif
  1078. #endif /* STM32_I2C_USE_I2C4 */
  1079. /*===========================================================================*/
  1080. /* Driver exported functions. */
  1081. /*===========================================================================*/
  1082. /**
  1083. * @brief Low level I2C driver initialization.
  1084. *
  1085. * @notapi
  1086. */
  1087. void i2c_lld_init(void) {
  1088. #if STM32_I2C_USE_I2C1
  1089. i2cObjectInit(&I2CD1);
  1090. I2CD1.thread = NULL;
  1091. I2CD1.i2c = I2C1;
  1092. #if STM32_I2C_USE_DMA == TRUE
  1093. I2CD1.dmarx = STM32_DMA_STREAM(STM32_I2C_I2C1_RX_DMA_STREAM);
  1094. I2CD1.dmatx = STM32_DMA_STREAM(STM32_I2C_I2C1_TX_DMA_STREAM);
  1095. #endif
  1096. #endif /* STM32_I2C_USE_I2C1 */
  1097. #if STM32_I2C_USE_I2C2
  1098. i2cObjectInit(&I2CD2);
  1099. I2CD2.thread = NULL;
  1100. I2CD2.i2c = I2C2;
  1101. #if STM32_I2C_USE_DMA == TRUE
  1102. I2CD2.dmarx = STM32_DMA_STREAM(STM32_I2C_I2C2_RX_DMA_STREAM);
  1103. I2CD2.dmatx = STM32_DMA_STREAM(STM32_I2C_I2C2_TX_DMA_STREAM);
  1104. #endif
  1105. #endif /* STM32_I2C_USE_I2C2 */
  1106. #if STM32_I2C_USE_I2C3
  1107. i2cObjectInit(&I2CD3);
  1108. I2CD3.thread = NULL;
  1109. I2CD3.i2c = I2C3;
  1110. #if STM32_I2C_USE_DMA == TRUE
  1111. I2CD3.dmarx = STM32_DMA_STREAM(STM32_I2C_I2C3_RX_DMA_STREAM);
  1112. I2CD3.dmatx = STM32_DMA_STREAM(STM32_I2C_I2C3_TX_DMA_STREAM);
  1113. #endif
  1114. #endif /* STM32_I2C_USE_I2C3 */
  1115. #if STM32_I2C_USE_I2C4
  1116. i2cObjectInit(&I2CD4);
  1117. I2CD4.thread = NULL;
  1118. I2CD4.i2c = I2C4;
  1119. #if STM32_I2C_USE_DMA == TRUE
  1120. I2CD4.dmarx = STM32_DMA_STREAM(STM32_I2C_I2C4_RX_DMA_STREAM);
  1121. I2CD4.dmatx = STM32_DMA_STREAM(STM32_I2C_I2C4_TX_DMA_STREAM);
  1122. #endif
  1123. #endif /* STM32_I2C_USE_I2C4 */
  1124. }
  1125. /**
  1126. * @brief Configures and activates the I2C peripheral.
  1127. *
  1128. * @param[in] i2cp pointer to the @p I2CDriver object
  1129. *
  1130. * @notapi
  1131. */
  1132. void i2c_lld_start(I2CDriver *i2cp) {
  1133. I2C_TypeDef *dp = i2cp->i2c;
  1134. #if STM32_I2C_USE_DMA == TRUE
  1135. /* Common DMA modes.*/
  1136. i2cp->txdmamode = DMAMODE_COMMON | STM32_DMA_CR_DIR_M2P;
  1137. i2cp->rxdmamode = DMAMODE_COMMON | STM32_DMA_CR_DIR_P2M;
  1138. #endif
  1139. /* Make sure I2C peripheral is disabled */
  1140. dp->CR1 &= ~I2C_CR1_PE;
  1141. i2cp->mode = i2cStopped;
  1142. /* If in stopped state then enables the I2C and DMA clocks.*/
  1143. if (i2cp->state == I2C_STOP) {
  1144. #if STM32_I2C_USE_I2C1
  1145. if (&I2CD1 == i2cp) {
  1146. rccResetI2C1();
  1147. rccEnableI2C1(FALSE);
  1148. #if STM32_I2C_USE_DMA == TRUE
  1149. {
  1150. bool b;
  1151. b = dmaStreamAllocate(i2cp->dmarx,
  1152. STM32_I2C_I2C1_IRQ_PRIORITY,
  1153. NULL,
  1154. (void *)i2cp);
  1155. osalDbgAssert(!b, "stream already allocated");
  1156. b = dmaStreamAllocate(i2cp->dmatx,
  1157. STM32_I2C_I2C1_IRQ_PRIORITY,
  1158. NULL,
  1159. (void *)i2cp);
  1160. osalDbgAssert(!b, "stream already allocated");
  1161. i2cp->rxdmamode |= STM32_DMA_CR_CHSEL(I2C1_RX_DMA_CHANNEL) |
  1162. STM32_DMA_CR_PL(STM32_I2C_I2C1_DMA_PRIORITY);
  1163. i2cp->txdmamode |= STM32_DMA_CR_CHSEL(I2C1_TX_DMA_CHANNEL) |
  1164. STM32_DMA_CR_PL(STM32_I2C_I2C1_DMA_PRIORITY);
  1165. }
  1166. #endif /* STM32_I2C_USE_DMA == TRUE */
  1167. #if defined(STM32_I2C1_GLOBAL_NUMBER) || defined(__DOXYGEN__)
  1168. nvicEnableVector(STM32_I2C1_GLOBAL_NUMBER, STM32_I2C_I2C1_IRQ_PRIORITY);
  1169. #elif defined(STM32_I2C1_EVENT_NUMBER) && defined(STM32_I2C1_ERROR_NUMBER)
  1170. nvicEnableVector(STM32_I2C1_EVENT_NUMBER, STM32_I2C_I2C1_IRQ_PRIORITY);
  1171. nvicEnableVector(STM32_I2C1_ERROR_NUMBER, STM32_I2C_I2C1_IRQ_PRIORITY);
  1172. #else
  1173. #error "I2C1 interrupt numbers not defined"
  1174. #endif
  1175. }
  1176. #endif /* STM32_I2C_USE_I2C1 */
  1177. #if STM32_I2C_USE_I2C2
  1178. if (&I2CD2 == i2cp) {
  1179. rccResetI2C2();
  1180. rccEnableI2C2(FALSE);
  1181. #if STM32_I2C_USE_DMA == TRUE
  1182. {
  1183. bool b;
  1184. b = dmaStreamAllocate(i2cp->dmarx,
  1185. STM32_I2C_I2C2_IRQ_PRIORITY,
  1186. NULL,
  1187. (void *)i2cp);
  1188. osalDbgAssert(!b, "stream already allocated");
  1189. b = dmaStreamAllocate(i2cp->dmatx,
  1190. STM32_I2C_I2C2_IRQ_PRIORITY,
  1191. NULL,
  1192. (void *)i2cp);
  1193. osalDbgAssert(!b, "stream already allocated");
  1194. i2cp->rxdmamode |= STM32_DMA_CR_CHSEL(I2C2_RX_DMA_CHANNEL) |
  1195. STM32_DMA_CR_PL(STM32_I2C_I2C2_DMA_PRIORITY);
  1196. i2cp->txdmamode |= STM32_DMA_CR_CHSEL(I2C2_TX_DMA_CHANNEL) |
  1197. STM32_DMA_CR_PL(STM32_I2C_I2C2_DMA_PRIORITY);
  1198. }
  1199. #endif /*STM32_I2C_USE_DMA == TRUE */
  1200. #if defined(STM32_I2C2_GLOBAL_NUMBER) || defined(__DOXYGEN__)
  1201. nvicEnableVector(STM32_I2C2_GLOBAL_NUMBER, STM32_I2C_I2C2_IRQ_PRIORITY);
  1202. #elif defined(STM32_I2C2_EVENT_NUMBER) && defined(STM32_I2C2_ERROR_NUMBER)
  1203. nvicEnableVector(STM32_I2C2_EVENT_NUMBER, STM32_I2C_I2C2_IRQ_PRIORITY);
  1204. nvicEnableVector(STM32_I2C2_ERROR_NUMBER, STM32_I2C_I2C2_IRQ_PRIORITY);
  1205. #else
  1206. #error "I2C2 interrupt numbers not defined"
  1207. #endif
  1208. }
  1209. #endif /* STM32_I2C_USE_I2C2 */
  1210. #if STM32_I2C_USE_I2C3
  1211. if (&I2CD3 == i2cp) {
  1212. rccResetI2C3();
  1213. rccEnableI2C3(FALSE);
  1214. #if STM32_I2C_USE_DMA == TRUE
  1215. {
  1216. bool b;
  1217. b = dmaStreamAllocate(i2cp->dmarx,
  1218. STM32_I2C_I2C3_IRQ_PRIORITY,
  1219. NULL,
  1220. (void *)i2cp);
  1221. osalDbgAssert(!b, "stream already allocated");
  1222. b = dmaStreamAllocate(i2cp->dmatx,
  1223. STM32_I2C_I2C3_IRQ_PRIORITY,
  1224. NULL,
  1225. (void *)i2cp);
  1226. osalDbgAssert(!b, "stream already allocated");
  1227. i2cp->rxdmamode |= STM32_DMA_CR_CHSEL(I2C3_RX_DMA_CHANNEL) |
  1228. STM32_DMA_CR_PL(STM32_I2C_I2C3_DMA_PRIORITY);
  1229. i2cp->txdmamode |= STM32_DMA_CR_CHSEL(I2C3_TX_DMA_CHANNEL) |
  1230. STM32_DMA_CR_PL(STM32_I2C_I2C3_DMA_PRIORITY);
  1231. }
  1232. #endif /*STM32_I2C_USE_DMA == TRUE */
  1233. #if defined(STM32_I2C3_GLOBAL_NUMBER) || defined(__DOXYGEN__)
  1234. nvicEnableVector(STM32_I2C3_GLOBAL_NUMBER, STM32_I2C_I2C3_IRQ_PRIORITY);
  1235. #elif defined(STM32_I2C3_EVENT_NUMBER) && defined(STM32_I2C3_ERROR_NUMBER)
  1236. nvicEnableVector(STM32_I2C3_EVENT_NUMBER, STM32_I2C_I2C3_IRQ_PRIORITY);
  1237. nvicEnableVector(STM32_I2C3_ERROR_NUMBER, STM32_I2C_I2C3_IRQ_PRIORITY);
  1238. #else
  1239. #error "I2C3 interrupt numbers not defined"
  1240. #endif
  1241. }
  1242. #endif /* STM32_I2C_USE_I2C3 */
  1243. #if STM32_I2C_USE_I2C4
  1244. if (&I2CD4 == i2cp) {
  1245. rccResetI2C4();
  1246. rccEnableI2C4(FALSE);
  1247. #if STM32_I2C_USE_DMA == TRUE
  1248. {
  1249. bool b;
  1250. b = dmaStreamAllocate(i2cp->dmarx,
  1251. STM32_I2C_I2C4_IRQ_PRIORITY,
  1252. NULL,
  1253. (void *)i2cp);
  1254. osalDbgAssert(!b, "stream already allocated");
  1255. b = dmaStreamAllocate(i2cp->dmatx,
  1256. STM32_I2C_I2C4_IRQ_PRIORITY,
  1257. NULL,
  1258. (void *)i2cp);
  1259. osalDbgAssert(!b, "stream already allocated");
  1260. i2cp->rxdmamode |= STM32_DMA_CR_CHSEL(I2C4_RX_DMA_CHANNEL) |
  1261. STM32_DMA_CR_PL(STM32_I2C_I2C4_DMA_PRIORITY);
  1262. i2cp->txdmamode |= STM32_DMA_CR_CHSEL(I2C4_TX_DMA_CHANNEL) |
  1263. STM32_DMA_CR_PL(STM32_I2C_I2C4_DMA_PRIORITY);
  1264. }
  1265. #endif /*STM32_I2C_USE_DMA == TRUE */
  1266. #if defined(STM32_I2C4_GLOBAL_NUMBER) || defined(__DOXYGEN__)
  1267. nvicEnableVector(STM32_I2C4_GLOBAL_NUMBER, STM32_I2C_I2C4_IRQ_PRIORITY);
  1268. #elif defined(STM32_I2C4_EVENT_NUMBER) && defined(STM32_I2C4_ERROR_NUMBER)
  1269. nvicEnableVector(STM32_I2C4_EVENT_NUMBER, STM32_I2C_I2C4_IRQ_PRIORITY);
  1270. nvicEnableVector(STM32_I2C4_ERROR_NUMBER, STM32_I2C_I2C4_IRQ_PRIORITY);
  1271. #else
  1272. #error "I2C4 interrupt numbers not defined"
  1273. #endif
  1274. }
  1275. #endif /* STM32_I2C_USE_I2C4 */
  1276. }
  1277. #if STM32_I2C_USE_DMA == TRUE
  1278. /* I2C registers pointed by the DMA.*/
  1279. dmaStreamSetPeripheral(i2cp->dmarx, &dp->RXDR);
  1280. dmaStreamSetPeripheral(i2cp->dmatx, &dp->TXDR);
  1281. /* Reset i2c peripheral, the TCIE bit will be handled separately. */
  1282. // TODO: Mask out config bits which user mustn't fiddle with
  1283. dp->CR1 = (i2cp->config->cr1 | I2C_CR1_ERRIE | I2C_CR1_NACKIE |
  1284. I2C_CR1_TXDMAEN | I2C_CR1_RXDMAEN);
  1285. #else
  1286. /* Reset i2c peripheral, the TCIE bit will be handled separately. No DMA interrupts */
  1287. dp->CR1 = (i2cp->config->cr1 | I2C_CR1_ERRIE | I2C_CR1_NACKIE);
  1288. #endif
  1289. /* Setup I2C parameters.*/
  1290. dp->TIMINGR = i2cp->config->timingr;
  1291. /* Ready to go.*/
  1292. i2cp->mode = i2cIdle;
  1293. #if HAL_USE_I2C_LOCK
  1294. i2cp->lockDuration = TIME_IMMEDIATE;
  1295. #endif
  1296. #if HAL_USE_I2C_SLAVE /* I2C slave mode support */
  1297. i2cp->slaveNextReply = i2cp->slaveNextRx = &I2CSlaveLockOnMsg;
  1298. i2cp->targetAdr = i2cInvalidAdr;
  1299. i2cp->slaveTimeout = TIME_INFINITE;
  1300. #endif
  1301. dp->CR1 |= I2C_CR1_PE; // Enable peripheral
  1302. }
  1303. /**
  1304. * @brief Deactivates the I2C peripheral.
  1305. *
  1306. * @param[in] i2cp pointer to the @p I2CDriver object
  1307. *
  1308. * @notapi
  1309. */
  1310. void i2c_lld_stop(I2CDriver *i2cp) {
  1311. /* If not in stopped state then disables the I2C clock.*/
  1312. if (i2cp->state != I2C_STOP) {
  1313. i2cp->mode = i2cStopped;
  1314. /* I2C disable.*/
  1315. stopTimer(i2cp);
  1316. i2c_lld_abort_operation(i2cp);
  1317. #if STM32_I2C_USE_DMA == TRUE
  1318. dmaStreamRelease(i2cp->dmatx);
  1319. dmaStreamRelease(i2cp->dmarx);
  1320. #endif
  1321. #if STM32_I2C_USE_I2C1
  1322. if (&I2CD1 == i2cp) {
  1323. #if defined(STM32_I2C1_GLOBAL_NUMBER) || defined(__DOXYGEN__)
  1324. nvicDisableVector(STM32_I2C1_GLOBAL_NUMBER);
  1325. #elif defined(STM32_I2C1_EVENT_NUMBER) && defined(STM32_I2C1_ERROR_NUMBER)
  1326. nvicDisableVector(STM32_I2C1_EVENT_NUMBER);
  1327. nvicDisableVector(STM32_I2C1_ERROR_NUMBER);
  1328. #else
  1329. #error "I2C1 interrupt numbers not defined"
  1330. #endif
  1331. rccDisableI2C1(FALSE);
  1332. }
  1333. #endif
  1334. #if STM32_I2C_USE_I2C2
  1335. if (&I2CD2 == i2cp) {
  1336. #if defined(STM32_I2C2_GLOBAL_NUMBER) || defined(__DOXYGEN__)
  1337. nvicDisableVector(STM32_I2C2_GLOBAL_NUMBER);
  1338. #elif defined(STM32_I2C2_EVENT_NUMBER) && defined(STM32_I2C2_ERROR_NUMBER)
  1339. nvicDisableVector(STM32_I2C2_EVENT_NUMBER);
  1340. nvicDisableVector(STM32_I2C2_ERROR_NUMBER);
  1341. #else
  1342. #error "I2C2 interrupt numbers not defined"
  1343. #endif
  1344. rccDisableI2C2(FALSE);
  1345. }
  1346. #endif
  1347. #if STM32_I2C_USE_I2C3
  1348. if (&I2CD3 == i2cp) {
  1349. #if defined(STM32_I2C3_GLOBAL_NUMBER) || defined(__DOXYGEN__)
  1350. nvicDisableVector(STM32_I2C3_GLOBAL_NUMBER);
  1351. #elif defined(STM32_I2C3_EVENT_NUMBER) && defined(STM32_I2C3_ERROR_NUMBER)
  1352. nvicDisableVector(STM32_I2C3_EVENT_NUMBER);
  1353. nvicDisableVector(STM32_I2C3_ERROR_NUMBER);
  1354. #else
  1355. #error "I2C3 interrupt numbers not defined"
  1356. #endif
  1357. rccDisableI2C3(FALSE);
  1358. }
  1359. #endif
  1360. #if STM32_I2C_USE_I2C4
  1361. if (&I2CD4 == i2cp) {
  1362. #if defined(STM32_I2C4_GLOBAL_NUMBER) || defined(__DOXYGEN__)
  1363. nvicDisableVector(STM32_I2C4_GLOBAL_NUMBER);
  1364. #elif defined(STM32_I2C4_EVENT_NUMBER) && defined(STM32_I2C4_ERROR_NUMBER)
  1365. nvicDisableVector(STM32_I2C4_EVENT_NUMBER);
  1366. nvicDisableVector(STM32_I2C4_ERROR_NUMBER);
  1367. #else
  1368. #error "I2C4 interrupt numbers not defined"
  1369. #endif
  1370. rccDisableI2C4(FALSE);
  1371. }
  1372. #endif
  1373. }
  1374. }
  1375. #if HAL_USE_I2C_MASTER == TRUE
  1376. /**
  1377. * Utility routine brings out common code for master timeout
  1378. */
  1379. static msg_t calcMasterTimeout(I2CDriver *i2cp)
  1380. {
  1381. systime_t start, end;
  1382. osalDbgAssert((i2cp->mode <= i2cIsMaster), "busy");
  1383. /* Calculating the time window for the timeout on the busy bus condition.*/
  1384. start = osalOsGetSystemTimeX();
  1385. end = start + OSAL_MS2ST(STM32_I2C_BUSY_TIMEOUT);
  1386. /* Waits until BUSY flag is reset or, alternatively, for a timeout
  1387. condition.*/
  1388. while (true) {
  1389. osalSysLock();
  1390. /* If the bus is not busy then the operation can continue, note, the
  1391. loop is exited in the locked state.*/
  1392. // if (!(i2cp->i2c->ISR & I2C_ISR_BUSY) && !(i2cp->i2c->CR1 & I2C_CR1_STOP))
  1393. if (!(i2cp->i2c->ISR & I2C_ISR_BUSY))
  1394. break;
  1395. /* If the system time went outside the allowed window then a timeout
  1396. condition is returned.*/
  1397. if (!osalOsIsTimeWithinX(osalOsGetSystemTimeX(), start, end))
  1398. return MSG_TIMEOUT;
  1399. osalSysUnlock();
  1400. // TODO: Should we relinquish thread here for a while?
  1401. chThdSleepMilliseconds(2);
  1402. }
  1403. i2cp->mode = i2cIsMaster; // We can set master mode now
  1404. return MSG_OK;
  1405. }
  1406. /**
  1407. * Start a master mode transaction
  1408. *
  1409. * Note: may need adjustment to work in multi-master mode as well - see i2c_lld_safety_timeout()
  1410. */
  1411. static msg_t startMasterAction(I2CDriver *i2cp, systime_t timeout)
  1412. {
  1413. #if STM32_I2C_USE_DMA == TRUE
  1414. #else
  1415. #endif
  1416. msg_t msg;
  1417. /* Starts the operation.*/
  1418. i2cp->i2c->CR2 |= I2C_CR2_START;
  1419. /* Waits for the operation completion or a timeout.*/
  1420. msg = osalThreadSuspendTimeoutS(&i2cp->thread, timeout);
  1421. /* In case of a software timeout a STOP is sent as an extreme attempt
  1422. to release the bus.*/
  1423. if (msg == MSG_TIMEOUT) {
  1424. i2cp->i2c->CR2 |= I2C_CR2_STOP;
  1425. i2cp->mode = i2cIdle; // TODO: Is this enough?
  1426. }
  1427. return msg;
  1428. }
  1429. /**
  1430. * @brief Receives data via the I2C bus as master.
  1431. * @details Number of receiving bytes must be more than 1 on STM32F1x. This is
  1432. * hardware restriction.
  1433. *
  1434. * @param[in] i2cp pointer to the @p I2CDriver object
  1435. * @param[in] addr slave device address
  1436. * @param[out] rxbuf pointer to the receive buffer
  1437. * @param[in] rxbytes number of bytes to be received
  1438. * @param[in] timeout the number of ticks before the operation timeouts,
  1439. * the following special values are allowed:
  1440. * - @a TIME_INFINITE no timeout.
  1441. * .
  1442. * @return The operation status.
  1443. * @retval MSG_OK if the function succeeded.
  1444. * @retval MSG_RESET if one or more I2C errors occurred, the errors can
  1445. * be retrieved using @p i2cGetErrors().
  1446. * @retval MSG_TIMEOUT if a timeout occurred before operation end. <b>After a
  1447. * timeout the driver must be stopped and restarted
  1448. * because the bus is in an uncertain state</b>.
  1449. *
  1450. * @notapi
  1451. */
  1452. msg_t i2c_lld_master_receive_timeout(I2CDriver *i2cp, i2caddr_t addr,
  1453. uint8_t *rxbuf, size_t rxbytes,
  1454. systime_t timeout) {
  1455. // I2C_TypeDef *dp = i2cp->i2c;
  1456. osalDbgAssert((i2cp->thread==NULL), "#3 - reentry");
  1457. /* Resetting error flags for this transfer.*/
  1458. i2cp->errors = I2C_NO_ERROR;
  1459. /* Releases the lock from high level driver.*/
  1460. osalSysUnlock();
  1461. calcMasterTimeout(i2cp); // This has to be done before we change the state of the connection
  1462. #if STM32_I2C_USE_DMA == TRUE
  1463. /* RX DMA setup.*/
  1464. dmaStreamSetMode(i2cp->dmarx, i2cp->rxdmamode);
  1465. dmaStreamSetMemory0(i2cp->dmarx, rxbuf);
  1466. dmaStreamSetTransactionSize(i2cp->dmarx, rxbytes);
  1467. #endif
  1468. // Always set up the receive buffer in case callbacks enabled
  1469. i2cp->rxptr = rxbuf;
  1470. i2cp->rxbytes = rxbytes;
  1471. /* Setting up the slave address.*/
  1472. i2c_lld_set_address(i2cp, addr);
  1473. /* Setting up the peripheral.*/
  1474. i2c_lld_setup_rx_transfer(i2cp);
  1475. i2cStartReceive(i2cp);
  1476. i2cp->mode = i2cMasterRxing;
  1477. return startMasterAction(i2cp, timeout);
  1478. }
  1479. /**
  1480. * @brief Transmits data via the I2C bus as master.
  1481. * @details Number of receiving bytes must be 0 or more than 1 on STM32F1x.
  1482. * This is hardware restriction.
  1483. *
  1484. * @param[in] i2cp pointer to the @p I2CDriver object
  1485. * @param[in] addr slave device address
  1486. * @param[in] txbuf pointer to the transmit buffer
  1487. * @param[in] txbytes number of bytes to be transmitted
  1488. * @param[out] rxbuf pointer to the receive buffer
  1489. * @param[in] rxbytes number of bytes to be received
  1490. * @param[in] timeout the number of ticks before the operation timeouts,
  1491. * the following special values are allowed:
  1492. * - @a TIME_INFINITE no timeout.
  1493. * .
  1494. * @return The operation status.
  1495. * @retval MSG_OK if the function succeeded.
  1496. * @retval MSG_RESET if one or more I2C errors occurred, the errors can
  1497. * be retrieved using @p i2cGetErrors().
  1498. * @retval MSG_TIMEOUT if a timeout occurred before operation end. <b>After a
  1499. * timeout the driver must be stopped and restarted
  1500. * because the bus is in an uncertain state</b>.
  1501. *
  1502. * @notapi
  1503. */
  1504. msg_t i2c_lld_master_transmit_timeout(I2CDriver *i2cp, i2caddr_t addr,
  1505. const uint8_t *txbuf, size_t txbytes,
  1506. uint8_t *rxbuf, size_t rxbytes,
  1507. systime_t timeout) {
  1508. I2C_TypeDef *dp = i2cp->i2c;
  1509. osalDbgAssert((i2cp->thread==NULL), "#3 - reentry");
  1510. /* Resetting error flags for this transfer.*/
  1511. i2cp->errors = I2C_NO_ERROR;
  1512. /* Releases the lock from high level driver.*/
  1513. osalSysUnlock();
  1514. calcMasterTimeout(i2cp); // This has to be done before we change the state of the connection
  1515. #if STM32_I2C_USE_DMA == TRUE
  1516. /* TX DMA setup.*/
  1517. dmaStreamSetMode(i2cp->dmatx, i2cp->txdmamode);
  1518. dmaStreamSetMemory0(i2cp->dmatx, txbuf);
  1519. dmaStreamSetTransactionSize(i2cp->dmatx, txbytes);
  1520. /* RX DMA setup, note, rxbytes can be zero but we write the value anyway.*/
  1521. dmaStreamSetMode(i2cp->dmarx, i2cp->rxdmamode);
  1522. dmaStreamSetMemory0(i2cp->dmarx, rxbuf);
  1523. dmaStreamSetTransactionSize(i2cp->dmarx, rxbytes);
  1524. #else
  1525. i2cp->txptr = txbuf;
  1526. i2cp->txbytes = txbytes;
  1527. #endif
  1528. // Always set up the receive buffer in case callbacks enabled
  1529. i2cp->rxptr = rxbuf;
  1530. i2cp->rxbytes = rxbytes;
  1531. /* Setting up the slave address.*/
  1532. i2c_lld_set_address(i2cp, addr);
  1533. /* Preparing the transfer.*/
  1534. i2c_lld_setup_tx_transfer(i2cp);
  1535. #if STM32_I2C_USE_DMA == TRUE
  1536. /* Enabling TX DMA.*/
  1537. dmaStreamEnable(i2cp->dmatx);
  1538. /* Transfer complete interrupt enabled.*/
  1539. dp->CR1 |= I2C_CR1_TCIE;
  1540. #else
  1541. /* Transfer complete and TX interrupts enabled.*/
  1542. dp->CR1 |= I2C_CR1_TCIE | I2C_CR1_TXIE;
  1543. #endif
  1544. i2cp->mode = i2cMasterTxing;
  1545. return startMasterAction(i2cp, timeout);
  1546. }
  1547. #endif /* #if HAL_USE_I2C_MASTER == TRUE */
  1548. #if HAL_USE_I2C_SLAVE
  1549. /************************************************************************/
  1550. /* SLAVE MODE SUPPORT */
  1551. /************************************************************************/
  1552. /**
  1553. * @brief Reconfigure I2C channel to respond to passed address
  1554. * in addition to those previously made active
  1555. *
  1556. * @param[in] i2cp pointer to the @p I2CDriver object
  1557. * @param[in] i2cadr I2C network address
  1558. *
  1559. * @return Length of message OR the type of event received
  1560. * @retval I2C_OK Success
  1561. * @retval I2C_ERROR Cannot match address in addition of those already
  1562. *
  1563. * @details MatchAddress calls are cumulative.
  1564. * Specify address zero to match I2C "all call"
  1565. * Does not support 10-bit addressing.
  1566. * Number of supported addresses is chip-dependent - 2+general call on I2CV2
  1567. * Address masking capabilities of OAR2 not supported
  1568. *
  1569. * @notapi
  1570. **/
  1571. msg_t i2c_lld_matchAddress(I2CDriver *i2cp, i2caddr_t i2cadr)
  1572. {
  1573. I2C_TypeDef *dp = i2cp->i2c;
  1574. if (i2cadr == 0) {
  1575. dp->CR1 |= I2C_CR1_GCEN; // Just enable General Call
  1576. dp->CR1 |= I2C_CR1_ADDRIE; // Make sure address match interrupt enabled
  1577. }
  1578. else
  1579. {
  1580. uint32_t adr = i2cadr << 1;
  1581. if ((dp->OAR1 & (0x7f<<1)) == adr) { return I2C_OK; }; // Already matched in OAR1
  1582. if ((dp->OAR2 & (0x7f<<1)) == adr) { return I2C_OK; }; // Already matched in OAR2
  1583. if (!(dp->OAR1 & I2C_OAR1_OA1EN)) {
  1584. dp->OAR1 = adr | I2C_OAR1_OA1EN; // OAR1 previously unused
  1585. dp->CR1 |= I2C_CR1_ADDRIE; // Make sure address match interrupt enabled
  1586. }
  1587. else
  1588. if (!(dp->OAR2 & I2C_OAR2_OA2EN)) {
  1589. dp->OAR2 = adr | I2C_OAR2_OA2EN; // OAR2 previously unused
  1590. dp->CR1 |= I2C_CR1_ADDRIE; // Make sure address match interrupt enabled
  1591. }
  1592. else
  1593. return I2C_ERROR; /* cannot add this address to set of those matched */
  1594. }
  1595. return I2C_OK;
  1596. }
  1597. /**
  1598. * @brief Reconfigure I2C channel to no longer match specified address
  1599. *
  1600. * @param[in] i2cp pointer to the @p I2CDriver object
  1601. * @param[in] i2cadr I2C network address
  1602. *
  1603. * @details A message being transferred that has already matched the
  1604. * specified address will continue being processed.
  1605. * Requests to unmatch an address that is not currently being matched
  1606. * are ignored.
  1607. * Does not support 10-bit addressing.
  1608. *
  1609. * @notapi
  1610. **/
  1611. void i2c_lld_unmatchAddress(I2CDriver *i2cp, i2caddr_t i2cadr)
  1612. {
  1613. I2C_TypeDef *dp = i2cp->i2c;
  1614. if (i2cadr == 0) {
  1615. dp->CR1 &= (uint32_t)~I2C_CR1_GCEN; // Disable General Call
  1616. }
  1617. else {
  1618. uint32_t adr = i2cadr << 1;
  1619. if ((dp->OAR1 & (0x7f<<1)) == adr) {
  1620. // Matched in OAR1
  1621. dp->OAR1 &= ~I2C_OAR1_OA1EN; // Just disable - OAR2 is a bit different
  1622. }
  1623. else
  1624. if ((dp->OAR2 & I2C_OAR2_OA2EN) && (dp->OAR2 & (0x7f<<1)) == adr)
  1625. dp->OAR2 &= ~I2C_OAR2_OA2EN;
  1626. }
  1627. if (!((dp->CR1 & (uint32_t)I2C_CR1_GCEN) || (dp->OAR1 & I2C_OAR1_OA1EN) || (dp->OAR2 & I2C_OAR2_OA2EN))) {
  1628. dp->CR1 &= (uint32_t)~(I2C_CR1_ADDRIE); // Disable Address match interrupts if nothing can generate them (strictly necessary??)
  1629. }
  1630. }
  1631. /**
  1632. * @brief Reconfigure I2C channel to no longer match any address
  1633. *
  1634. * @param[in] i2cp pointer to the @p I2CDriver object
  1635. *
  1636. * @details Causes all subsequent messages to be ignored.
  1637. * A message being transferred that has already matched a
  1638. * slave address will continue being processed.
  1639. *
  1640. * @notapi
  1641. **/
  1642. void i2c_lld_unmatchAll(I2CDriver *i2cp)
  1643. {
  1644. I2C_TypeDef *dp = i2cp->i2c;
  1645. dp->CR1 &= (uint32_t)~(I2C_CR1_GCEN | I2C_CR1_ADDRIE); // Disable General Call
  1646. dp->OAR1 = 0;
  1647. dp->OAR2 = 0;
  1648. }
  1649. /**
  1650. * @brief Configure callbacks & buffers to receive messages
  1651. *
  1652. * @param[in] i2cp pointer to the @p I2CDriver object
  1653. * @param[in] replyMsg @p I2CSlaveMsg struct for processing subsequent received messages
  1654. *
  1655. * @details Call i2cMatchAddress() after this to start processing
  1656. * Enabling match addresses before installing handler callbacks can
  1657. * result in locking the I2C bus when a master accesses those
  1658. * unconfigured slave addresses
  1659. *
  1660. * @notapi
  1661. */
  1662. void i2c_lld_slaveReceive(I2CDriver *i2cp, const I2CSlaveMsg *rxMsg)
  1663. {
  1664. osalDbgCheck((rxMsg && rxMsg->size <= 0xffff));
  1665. qEvt(0x82, rxMsg->size);
  1666. i2cp->slaveNextRx = rxMsg;
  1667. if (i2cp->mode == i2cLockedRxing && rxMsg->body && rxMsg->size) {
  1668. /* We can receive now! */
  1669. i2cp->slaveRx = rxMsg;
  1670. /* slave RX DMA setup */
  1671. #if STM32_I2C_USE_DMA == TRUE
  1672. /* RX DMA setup.*/
  1673. dmaStreamSetMode(i2cp->dmarx, i2cp->rxdmamode);
  1674. dmaStreamSetMemory0(i2cp->dmarx, rxMsg->body);
  1675. dmaStreamSetTransactionSize(i2cp->dmarx, rxMsg->size);
  1676. #else
  1677. i2cp->rxptr = rxMsg->body;
  1678. i2cp->rxbytes = rxMsg->size;
  1679. #endif
  1680. i2cp->mode = i2cSlaveRxing;
  1681. i2c_lld_setup_rx_transfer(i2cp); // Set up the transfer
  1682. qEvt(0x83, 0);
  1683. i2cStartReceive(i2cp);
  1684. i2cp->i2c->CR1 &= ~I2C_CR1_SBC; // Not needed with receive
  1685. i2cp->i2c->ICR = I2C_ISR_ADDR; // We can release the clock stretch now
  1686. }
  1687. }
  1688. /**
  1689. * @brief Configure callbacks & buffers for query reply
  1690. *
  1691. * @param[in] i2cp pointer to the @p I2CDriver object
  1692. * @param[in] replyMsg @p I2CSlaveMsg struct for processing subsequent queries
  1693. *
  1694. * @details Call i2cMatchAddress() after this to start processing
  1695. * Enabling match addresses before installing handler callbacks can
  1696. * result in locking the I2C bus when a master accesses those
  1697. * unconfigured slave addresses
  1698. *
  1699. * @notapi
  1700. */
  1701. void i2c_lld_slaveReply(I2CDriver *i2cp, const I2CSlaveMsg *replyMsg)
  1702. {
  1703. osalDbgCheck((replyMsg && replyMsg->size <= 0xffff));
  1704. qEvt(0x80, replyMsg->size);
  1705. i2cp->slaveNextReply = replyMsg;
  1706. if (i2cp->mode == i2cLockedReplying && replyMsg->body && replyMsg->size)
  1707. {
  1708. i2cp->slaveReply = replyMsg;
  1709. /* slave TX setup -- we can reply now! */
  1710. #if STM32_I2C_USE_DMA == TRUE
  1711. dmaStreamSetMode(i2cp->dmatx, i2cp->txdmamode);
  1712. dmaStreamSetMemory0(i2cp->dmatx, replyMsg->body);
  1713. dmaStreamSetTransactionSize(i2cp->dmatx, replyMsg->size);
  1714. i2cp->mode = i2cSlaveReplying;
  1715. /* Start transmission */
  1716. i2c_lld_setup_tx_transfer(i2cp);
  1717. /* Enabling TX DMA.*/
  1718. dmaStreamEnable(i2cp->dmatx);
  1719. /* Transfer complete interrupt enabled.*/
  1720. i2cp->i2c->CR1 |= I2C_CR1_TCIE;
  1721. #else
  1722. /* Start transmission */
  1723. i2cp->txptr = replyMsg->body;
  1724. i2cp->txbytes = replyMsg->size;
  1725. i2c_lld_setup_tx_transfer(i2cp);
  1726. /* Transfer complete and TX character interrupts enabled.*/
  1727. i2cp->i2c->CR1 |= I2C_CR1_TCIE | I2C_CR1_TXIE;
  1728. #endif
  1729. qEvt(0x81, 0);
  1730. i2cp->i2c->CR1 |= I2C_CR1_SBC; // Need this to enable byte counter in transmit mode
  1731. i2cp->i2c->ICR = I2C_ISR_ADDR; // We can release the clock stretch now
  1732. }
  1733. }
  1734. #endif /* HAL_USE_I2C_SLAVE */
  1735. #endif /* HAL_USE_I2C */
  1736. /** @} */