PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

před 3 roky
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. /*
  2. ------------------------------------------------------------------------------------------------------
  3. i2c_t3 - I2C library for Teensy 3.x & LC
  4. - (v11.0) Modified 01Dec18 by Brian (nox771 at gmail.com)
  5. Full changelog at end of file
  6. ------------------------------------------------------------------------------------------------------
  7. Copyright (c) 2013-2018, Brian (nox771 at gmail.com)
  8. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
  9. associated documentation files (the "Software"), to deal in the Software without restriction,
  10. including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
  11. and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
  12. subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in all copies or substantial
  14. portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
  16. LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  17. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  19. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20. ------------------------------------------------------------------------------------------------------
  21. */
  22. #if defined(__AVR__)
  23. #error "Sorry, i2c_t3 only works on Teensy LC and 3.x boards. Use Wire for Teensy 2.0."
  24. #endif
  25. #if !defined(I2C_T3_H) && (defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MKL26Z64__) || \
  26. defined(__MK64FX512__) || defined(__MK66FX1M0__)) // 3.0/3.1-3.2/LC/3.5/3.6
  27. #define I2C_T3_H
  28. #include <inttypes.h>
  29. #include <stdio.h> // for size_t
  30. #include "Arduino.h"
  31. #include <DMAChannel.h>
  32. // TODO missing kinetis.h defs
  33. #ifndef I2C_F_DIV52
  34. #define I2C_F_DIV52 ((uint8_t)0x43)
  35. #define I2C_F_DIV60 ((uint8_t)0x45)
  36. #define I2C_F_DIV136 ((uint8_t)0x4F)
  37. #define I2C_F_DIV176 ((uint8_t)0x55)
  38. #define I2C_F_DIV352 ((uint8_t)0x95)
  39. #define I2C_FLT_SSIE ((uint8_t)0x20) // Start/Stop Interrupt Enable
  40. #define I2C_FLT_STARTF ((uint8_t)0x10) // Start Detect Flag
  41. #endif
  42. // ======================================================================================================
  43. // == Start User Define Section =========================================================================
  44. // ======================================================================================================
  45. // ------------------------------------------------------------------------------------------------------
  46. // I2C Bus Enable control - change to enable buses as follows. The number of buses will be limited to the
  47. // lower of this setting or what is available on the device.
  48. //
  49. // Teensy Max #Buses
  50. // ------ ----------
  51. // LC 2
  52. // 3.0 1
  53. // 3.1 2
  54. // 3.2 2
  55. // 3.5 3
  56. // 3.6 4
  57. //
  58. // I2C_BUS_ENABLE 1 (enable Wire only)
  59. // I2C_BUS_ENABLE 2 (enable Wire & Wire1)
  60. // I2C_BUS_ENABLE 3 (enable Wire & Wire1 & Wire2)
  61. // I2C_BUS_ENABLE 4 (enable Wire & Wire1 & Wire2 & Wire3)
  62. //
  63. #define I2C_BUS_ENABLE 4
  64. // ------------------------------------------------------------------------------------------------------
  65. // Tx/Rx buffer sizes - modify these as needed. Buffers should be large enough to hold:
  66. // Target Addr + Data payload. Default is: 1byte Addr + 258byte Data
  67. // (this can be substantially reduced if working with sensors or small data packets)
  68. //
  69. #define I2C_TX_BUFFER_LENGTH 259
  70. #define I2C_RX_BUFFER_LENGTH 259
  71. // ------------------------------------------------------------------------------------------------------
  72. // Interrupt flag - uncomment and set below to make the specified pin high whenever the
  73. // I2C interrupt occurs (modify pin number as needed). This is useful as a
  74. // trigger signal when using a logic analyzer.
  75. //
  76. //#define I2C0_INTR_FLAG_PIN 5
  77. //#define I2C1_INTR_FLAG_PIN 6
  78. //#define I2C2_INTR_FLAG_PIN 9
  79. //#define I2C3_INTR_FLAG_PIN 10
  80. // ------------------------------------------------------------------------------------------------------
  81. // Auto retry - uncomment to make the library automatically call resetBus() if it has a timeout while
  82. // trying to send a START (occurs at the beginning of any endTransmission() or requestFrom()
  83. // call). This will toggle SCL to try and get a hung Slave device to release the SDA line.
  84. // If successful then it will try again to send a START, if not then it will return a timeout
  85. // error (same as if auto retry was not defined).
  86. //
  87. // Note: this is incompatible with multi-master buses, only use in single-master configurations
  88. //
  89. //#define I2C_AUTO_RETRY
  90. // ------------------------------------------------------------------------------------------------------
  91. // Error counters - uncomment to make the library track error counts. Error counts can be retrieved or
  92. // zeroed using the getErrorCount() and zeroErrorCount() functions respectively.
  93. // When included, errors will be tracked on the following (Master-mode only):
  94. // Reset Bus (auto-retry only), Timeout, Addr NAK, Data NAK, Arb Lost, Bus Not Acquired,
  95. // DMA Errors
  96. //
  97. #define I2C_ERROR_COUNTERS
  98. // ------------------------------------------------------------------------------------------------------
  99. // Disable priority check - uncomment this to entirely disable auto priority escalation. Normally
  100. // priority escalation occurs to ensure I2C ISR operates at a higher priority
  101. // than the calling function (to prevent ISR stall if the calling function
  102. // blocks). Uncommenting this will disable the check and cause I2C ISR to
  103. // remain at default priority. It is recommended to disable this check and
  104. // manually set ISR priority levels when using complex configurations.
  105. //
  106. //#define I2C_DISABLE_PRIORITY_CHECK
  107. // ======================================================================================================
  108. // == End User Define Section ===========================================================================
  109. // ======================================================================================================
  110. // ------------------------------------------------------------------------------------------------------
  111. // Set number of enabled buses
  112. //
  113. #if defined(__MK20DX128__) // 3.0
  114. #define I2C_BUS_NUM 1
  115. #elif (defined(__MK20DX256__) || defined(__MKL26Z64__)) && (I2C_BUS_ENABLE >= 2) // 3.1/3.2/LC
  116. #define I2C_BUS_NUM 2
  117. #elif defined(__MK64FX512__) && (I2C_BUS_ENABLE >= 3) // 3.5
  118. #define I2C_BUS_NUM 3
  119. #elif defined(__MK66FX1M0__) && (I2C_BUS_ENABLE >= 4) // 3.6
  120. #define I2C_BUS_NUM 4
  121. #else
  122. #define I2C_BUS_NUM I2C_BUS_ENABLE
  123. #endif
  124. // ------------------------------------------------------------------------------------------------------
  125. // Interrupt flag setup
  126. //
  127. #if defined(I2C0_INTR_FLAG_PIN)
  128. #define I2C0_INTR_FLAG_INIT do \
  129. { \
  130. pinMode(I2C0_INTR_FLAG_PIN, OUTPUT); \
  131. digitalWrite(I2C0_INTR_FLAG_PIN, LOW); \
  132. } while(0)
  133. #define I2C0_INTR_FLAG_ON do {digitalWrite(I2C0_INTR_FLAG_PIN, HIGH);} while(0)
  134. #define I2C0_INTR_FLAG_OFF do {digitalWrite(I2C0_INTR_FLAG_PIN, LOW);} while(0)
  135. #else
  136. #define I2C0_INTR_FLAG_INIT do{}while(0)
  137. #define I2C0_INTR_FLAG_ON do{}while(0)
  138. #define I2C0_INTR_FLAG_OFF do{}while(0)
  139. #endif
  140. #if defined(I2C1_INTR_FLAG_PIN)
  141. #define I2C1_INTR_FLAG_INIT do \
  142. { \
  143. pinMode(I2C1_INTR_FLAG_PIN, OUTPUT); \
  144. digitalWrite(I2C1_INTR_FLAG_PIN, LOW); \
  145. } while(0)
  146. #define I2C1_INTR_FLAG_ON do {digitalWrite(I2C1_INTR_FLAG_PIN, HIGH);} while(0)
  147. #define I2C1_INTR_FLAG_OFF do {digitalWrite(I2C1_INTR_FLAG_PIN, LOW);} while(0)
  148. #else
  149. #define I2C1_INTR_FLAG_INIT do{}while(0)
  150. #define I2C1_INTR_FLAG_ON do{}while(0)
  151. #define I2C1_INTR_FLAG_OFF do{}while(0)
  152. #endif
  153. #if defined(I2C2_INTR_FLAG_PIN)
  154. #define I2C2_INTR_FLAG_INIT do \
  155. { \
  156. pinMode(I2C2_INTR_FLAG_PIN, OUTPUT); \
  157. digitalWrite(I2C2_INTR_FLAG_PIN, LOW); \
  158. } while(0)
  159. #define I2C2_INTR_FLAG_ON do {digitalWrite(I2C2_INTR_FLAG_PIN, HIGH);} while(0)
  160. #define I2C2_INTR_FLAG_OFF do {digitalWrite(I2C2_INTR_FLAG_PIN, LOW);} while(0)
  161. #else
  162. #define I2C2_INTR_FLAG_INIT do{}while(0)
  163. #define I2C2_INTR_FLAG_ON do{}while(0)
  164. #define I2C2_INTR_FLAG_OFF do{}while(0)
  165. #endif
  166. #if defined(I2C3_INTR_FLAG_PIN)
  167. #define I2C3_INTR_FLAG_INIT do \
  168. { \
  169. pinMode(I2C3_INTR_FLAG_PIN, OUTPUT); \
  170. digitalWrite(I2C3_INTR_FLAG_PIN, LOW); \
  171. } while(0)
  172. #define I2C3_INTR_FLAG_ON do {digitalWrite(I2C3_INTR_FLAG_PIN, HIGH);} while(0)
  173. #define I2C3_INTR_FLAG_OFF do {digitalWrite(I2C3_INTR_FLAG_PIN, LOW);} while(0)
  174. #else
  175. #define I2C3_INTR_FLAG_INIT do{}while(0)
  176. #define I2C3_INTR_FLAG_ON do{}while(0)
  177. #define I2C3_INTR_FLAG_OFF do{}while(0)
  178. #endif
  179. // ------------------------------------------------------------------------------------------------------
  180. // Error counters setup
  181. //
  182. #if defined(I2C_ERROR_COUNTERS)
  183. #define I2C_ERR_INC(i2c_err_count) do {if(i2c->errCounts[i2c_err_count] < UINT32_MAX) i2c->errCounts[i2c_err_count]++;} while(0)
  184. #else
  185. #define I2C_ERR_INC(i2c_err_count) do{}while(0)
  186. #endif
  187. // ------------------------------------------------------------------------------------------------------
  188. // Function argument enums
  189. //
  190. enum i2c_op_mode {I2C_OP_MODE_IMM, I2C_OP_MODE_ISR, I2C_OP_MODE_DMA};
  191. enum i2c_mode {I2C_MASTER, I2C_SLAVE};
  192. enum i2c_pullup {I2C_PULLUP_EXT, I2C_PULLUP_INT};
  193. enum i2c_rate {I2C_RATE_100 = 100000,
  194. I2C_RATE_200 = 200000,
  195. I2C_RATE_300 = 300000,
  196. I2C_RATE_400 = 400000,
  197. I2C_RATE_600 = 600000,
  198. I2C_RATE_800 = 800000,
  199. I2C_RATE_1000 = 1000000,
  200. I2C_RATE_1200 = 1200000,
  201. I2C_RATE_1500 = 1500000,
  202. I2C_RATE_1800 = 1800000,
  203. I2C_RATE_2000 = 2000000,
  204. I2C_RATE_2400 = 2400000,
  205. I2C_RATE_2800 = 2800000,
  206. I2C_RATE_3000 = 3000000};
  207. enum i2c_stop {I2C_NOSTOP, I2C_STOP};
  208. enum i2c_status {I2C_WAITING, // stopped states
  209. I2C_TIMEOUT, // |
  210. I2C_ADDR_NAK, // |
  211. I2C_DATA_NAK, // |
  212. I2C_ARB_LOST, // |
  213. I2C_BUF_OVF, // |
  214. I2C_NOT_ACQ, // |
  215. I2C_DMA_ERR, // V
  216. I2C_SENDING, // active states
  217. I2C_SEND_ADDR, // |
  218. I2C_RECEIVING, // |
  219. I2C_SLAVE_TX, // |
  220. I2C_SLAVE_RX}; // V
  221. enum i2c_dma_state {I2C_DMA_OFF,
  222. I2C_DMA_ADDR,
  223. I2C_DMA_BULK,
  224. I2C_DMA_LAST};
  225. #if defined(__MKL26Z64__) // LC
  226. enum i2c_pins {I2C_PINS_16_17 = 0, // 16 SCL0 17 SDA0
  227. I2C_PINS_18_19, // 19 SCL0 18 SDA0
  228. I2C_PINS_22_23, // 22 SCL1 23 SDA1
  229. I2C_PINS_DEFAULT,
  230. I2C_PINS_COUNT};
  231. const uint8_t i2c_valid_pins[] = { 0, 16, 17, 2, // bus, scl, sda, alt
  232. 0, 19, 18, 2,
  233. 1, 22, 23, 2,
  234. 0, 0, 0, 0 };
  235. #elif defined(__MK20DX128__) // 3.0
  236. enum i2c_pins {I2C_PINS_16_17 = 0, // 16 SCL0 17 SDA0
  237. I2C_PINS_18_19, // 19 SCL0 18 SDA0
  238. I2C_PINS_DEFAULT,
  239. I2C_PINS_COUNT};
  240. const uint8_t i2c_valid_pins[] = { 0, 16, 17, 2, // bus, scl, sda, alt
  241. 0, 19, 18, 2,
  242. 0, 0, 0, 0 };
  243. #elif defined(__MK20DX256__) // 3.1/3.2
  244. enum i2c_pins {I2C_PINS_16_17 = 0, // 16 SCL0 17 SDA0
  245. I2C_PINS_18_19, // 19 SCL0 18 SDA0
  246. I2C_PINS_29_30, // 29 SCL1 30 SDA1
  247. I2C_PINS_26_31, // 26 SCL1 31 SDA1
  248. I2C_PINS_DEFAULT,
  249. I2C_PINS_COUNT};
  250. const uint8_t i2c_valid_pins[] = { 0, 16, 17, 2, // bus, scl, sda, alt
  251. 0, 19, 18, 2,
  252. 1, 29, 30, 2,
  253. 1, 26, 31, 6,
  254. 0, 0, 0, 0 };
  255. #elif defined(__MK64FX512__) // 3.5
  256. enum i2c_pins {I2C_PINS_3_4 = 0, // 3 SCL2 4 SDA2
  257. I2C_PINS_7_8, // 7 SCL0 8 SDA0
  258. I2C_PINS_16_17, // 16 SCL0 17 SDA0
  259. I2C_PINS_18_19, // 19 SCL0 18 SDA0
  260. I2C_PINS_33_34, // 33 SCL0 34 SDA0
  261. I2C_PINS_37_38, // 37 SCL1 38 SDA1
  262. I2C_PINS_47_48, // 47 SCL0 48 SDA0
  263. I2C_PINS_DEFAULT,
  264. I2C_PINS_COUNT};
  265. const uint8_t i2c_valid_pins[] = { 2, 3, 4, 5, // bus, scl, sda, alt
  266. 0, 7, 8, 7,
  267. 0, 16, 17, 2,
  268. 0, 19, 18, 2,
  269. 0, 33, 34, 5,
  270. 1, 37, 38, 2,
  271. 0, 47, 48, 2,
  272. 0, 0, 0, 0 };
  273. #elif defined(__MK66FX1M0__) // 3.6
  274. enum i2c_pins {I2C_PINS_3_4 = 0, // 3 SCL2 4 SDA2
  275. I2C_PINS_7_8, // 7 SCL0 8 SDA0
  276. I2C_PINS_16_17, // 16 SCL0 17 SDA0
  277. I2C_PINS_18_19, // 19 SCL0 18 SDA0
  278. I2C_PINS_33_34, // 33 SCL0 34 SDA0
  279. I2C_PINS_37_38, // 37 SCL1 38 SDA1
  280. I2C_PINS_47_48, // 47 SCL0 48 SDA0
  281. I2C_PINS_56_57, // 57 SCL3 56 SDA3
  282. I2C_PINS_DEFAULT,
  283. I2C_PINS_COUNT};
  284. const uint8_t i2c_valid_pins[] = { 2, 3, 4, 5, // bus, scl, sda, alt
  285. 0, 7, 8, 7,
  286. 0, 16, 17, 2,
  287. 0, 19, 18, 2,
  288. 0, 33, 34, 5,
  289. 1, 37, 38, 2,
  290. 0, 47, 48, 2,
  291. 3, 57, 56, 2,
  292. 0, 0, 0, 0 };
  293. #endif
  294. enum i2c_err_count {I2C_ERRCNT_RESET_BUS=0,
  295. I2C_ERRCNT_TIMEOUT,
  296. I2C_ERRCNT_ADDR_NAK,
  297. I2C_ERRCNT_DATA_NAK,
  298. I2C_ERRCNT_ARBL,
  299. I2C_ERRCNT_NOT_ACQ,
  300. I2C_ERRCNT_DMA_ERR};
  301. // ------------------------------------------------------------------------------------------------------
  302. // Divide ratio tables
  303. //
  304. const int32_t i2c_div_num[] =
  305. {20,22,24,26,28,30,32,34,36,40,44,48,52,56,60,64,68,72,
  306. 80,88,96,104,112,128,136,144,160,176,192,224,240,256,288,
  307. 320,352,384,448,480,512,576,640,768,896,960,1024,1152,
  308. 1280,1536,1920,1792,2048,2304,2560,3072,3840};
  309. const uint8_t i2c_div_ratio[] =
  310. {I2C_F_DIV20,I2C_F_DIV22,I2C_F_DIV24,I2C_F_DIV26,
  311. I2C_F_DIV28,I2C_F_DIV30,I2C_F_DIV32,I2C_F_DIV34,
  312. I2C_F_DIV36,I2C_F_DIV40,I2C_F_DIV44,I2C_F_DIV48,
  313. I2C_F_DIV52,I2C_F_DIV56,I2C_F_DIV60,I2C_F_DIV64,
  314. I2C_F_DIV68,I2C_F_DIV72,I2C_F_DIV80,I2C_F_DIV88,
  315. I2C_F_DIV96,I2C_F_DIV104,I2C_F_DIV112,I2C_F_DIV128,
  316. I2C_F_DIV136,I2C_F_DIV144,I2C_F_DIV160,I2C_F_DIV176,
  317. I2C_F_DIV192,I2C_F_DIV224,I2C_F_DIV240,I2C_F_DIV256,
  318. I2C_F_DIV288,I2C_F_DIV320,I2C_F_DIV352,I2C_F_DIV384,
  319. I2C_F_DIV448,I2C_F_DIV480,I2C_F_DIV512,I2C_F_DIV576,
  320. I2C_F_DIV640,I2C_F_DIV768,I2C_F_DIV896,I2C_F_DIV960,
  321. I2C_F_DIV1024,I2C_F_DIV1152,I2C_F_DIV1280,I2C_F_DIV1536,
  322. I2C_F_DIV1920,I2C_F_DIV1792,I2C_F_DIV2048,I2C_F_DIV2304,
  323. I2C_F_DIV2560,I2C_F_DIV3072,I2C_F_DIV3840};
  324. // ------------------------------------------------------------------------------------------------------
  325. // Main I2C data structure
  326. //
  327. struct i2cStruct
  328. {
  329. volatile uint8_t* A1; // Address Register 1 (User&ISR)
  330. volatile uint8_t* F; // Frequency Divider Register (User&ISR)
  331. volatile uint8_t* C1; // Control Register 1 (User&ISR)
  332. volatile uint8_t* S; // Status Register (User&ISR)
  333. volatile uint8_t* D; // Data I/O Register (User&ISR)
  334. volatile uint8_t* C2; // Control Register 2 (User&ISR)
  335. volatile uint8_t* FLT; // Programmable Input Glitch Filter (User&ISR)
  336. volatile uint8_t* RA; // Range Address Register (User&ISR)
  337. volatile uint8_t* SMB; // SMBus Control and Status Register (User&ISR)
  338. volatile uint8_t* A2; // Address Register 2 (User&ISR)
  339. volatile uint8_t* SLTH; // SCL Low Timeout Register High (User&ISR)
  340. volatile uint8_t* SLTL; // SCL Low Timeout Register Low (User&ISR)
  341. uint8_t rxBuffer[I2C_RX_BUFFER_LENGTH]; // Rx Buffer (ISR)
  342. volatile size_t rxBufferIndex; // Rx Index (User&ISR)
  343. volatile size_t rxBufferLength; // Rx Length (ISR)
  344. uint8_t txBuffer[I2C_TX_BUFFER_LENGTH]; // Tx Buffer (User)
  345. volatile size_t txBufferIndex; // Tx Index (User&ISR)
  346. volatile size_t txBufferLength; // Tx Length (User&ISR)
  347. i2c_op_mode opMode; // Operating Mode (User)
  348. i2c_mode currentMode; // Current Mode (User)
  349. volatile uint8_t currentSCL; // Current SCL pin (User&ISR)
  350. volatile uint8_t currentSDA; // Current SDA pin (User&ISR)
  351. i2c_pullup currentPullup; // Current Pullup (User)
  352. uint32_t currentRate; // Current Rate (User)
  353. i2c_stop currentStop; // Current Stop (User)
  354. volatile i2c_status currentStatus; // Current Status (User&ISR)
  355. uint8_t rxAddr; // Rx Address (ISR)
  356. size_t reqCount; // Byte Request Count (User)
  357. uint8_t irqCount; // IRQ Count, used by SDA-rising ISR (ISR)
  358. uint8_t timeoutRxNAK; // Rx Timeout NAK flag (ISR)
  359. volatile i2c_dma_state activeDMA; // Active DMA flag (User&ISR)
  360. void (*user_onTransmitDone)(void); // Master Tx Callback Function (User)
  361. void (*user_onReqFromDone)(void); // Master Rx Callback Function (User)
  362. void (*user_onReceive)(size_t len); // Slave Rx Callback Function (User)
  363. void (*user_onRequest)(void); // Slave Tx Callback Function (User)
  364. void (*user_onError)(void); // Error Callback Function (User)
  365. DMAChannel* DMA; // DMA Channel object (User&ISR)
  366. uint32_t defTimeout; // Default Timeout (User)
  367. volatile uint32_t errCounts[7]; // Error Counts Array (User&ISR)
  368. uint8_t configuredSCL; // SCL configured flag (User)
  369. uint8_t configuredSDA; // SDA configured flag (User)
  370. };
  371. // ------------------------------------------------------------------------------------------------------
  372. // I2C Class
  373. //
  374. extern "C" void i2c0_isr(void);
  375. #if I2C_BUS_NUM >= 2
  376. extern "C" void i2c1_isr(void);
  377. #endif
  378. #if I2C_BUS_NUM >= 3
  379. extern "C" void i2c2_isr(void);
  380. #endif
  381. #if I2C_BUS_NUM >= 4
  382. extern "C" void i2c3_isr(void);
  383. #endif
  384. extern "C" void i2c_isr_handler(struct i2cStruct* i2c, uint8_t bus);
  385. class i2c_t3 : public Stream
  386. {
  387. private:
  388. //
  389. // I2C data structures - these need to be static so "C" ISRs can use them
  390. //
  391. static struct i2cStruct i2cData[I2C_BUS_NUM];
  392. //
  393. // Base handler - ISRs are non-class global functions, friend of class req'd for data access
  394. //
  395. friend void i2c_isr_handler(struct i2cStruct* i2c, uint8_t bus);
  396. //
  397. // Bus ISRs
  398. //
  399. friend void i2c0_isr(void); // I2C0 ISR
  400. #if (defined(__MK20DX128__) || defined(__MK20DX256__))
  401. static void sda_rising_isr_handler(struct i2cStruct* i2c, uint8_t bus); // Slave STOP base handler - 3.0/3.1/3.2 only
  402. static void sda0_rising_isr(void); // Slave STOP detection (I2C0) - 3.0/3.1/3.2 only
  403. #endif
  404. #if I2C_BUS_NUM >= 2
  405. friend void i2c1_isr(void); // I2C1 ISR
  406. #if defined(__MK20DX256__)
  407. static void sda1_rising_isr(void); // Slave STOP detection (I2C1) - 3.1/3.2 only
  408. #endif
  409. #endif
  410. #if I2C_BUS_NUM >= 3
  411. friend void i2c2_isr(void); // I2C2 ISR
  412. #endif
  413. #if I2C_BUS_NUM >= 4
  414. friend void i2c3_isr(void); // I2C3 ISR
  415. #endif
  416. public:
  417. //
  418. // I2C bus number - this is a local, passed as an argument to base functions
  419. // since static functions cannot see it.
  420. uint8_t bus;
  421. //
  422. // I2C structure pointer - this is a local, passed as an argument to base functions
  423. // since static functions cannot see it.
  424. struct i2cStruct* i2c;
  425. //
  426. // I2C ISR Active flag - this is used to disable priority escalation. Increment to 1 to disable priority
  427. // check. This is a global flag to prevent complex cross-bus issues. It is only
  428. // incremented/decremented, not set.
  429. //
  430. static volatile uint8_t isrActive;
  431. // ------------------------------------------------------------------------------------------------------
  432. // Constructor
  433. //
  434. i2c_t3(uint8_t i2c_bus);
  435. ~i2c_t3();
  436. // ------------------------------------------------------------------------------------------------------
  437. // Pin Mapping - convert i2c_pins enum into pin values, intended for internal use only
  438. //
  439. inline uint8_t mapSCL(i2c_pins pins) { return i2c_valid_pins[pins*4+1]; }
  440. inline uint8_t mapSDA(i2c_pins pins) { return i2c_valid_pins[pins*4+2]; }
  441. // ------------------------------------------------------------------------------------------------------
  442. // Valid pin checks - verify if SCL or SDA pin is valid, intended for internal use only
  443. // return: alt setting, 0=not valid
  444. // parameters:
  445. // bus = bus number
  446. // pin = pin number to check
  447. // offset = array offset
  448. //
  449. static uint8_t validPin_(uint8_t bus, uint8_t pin, uint8_t offset);
  450. // ------------------------------------------------------------------------------------------------------
  451. // Initialize I2C (base routine)
  452. //
  453. static void begin_(struct i2cStruct* i2c, uint8_t bus, i2c_mode mode, uint8_t address1, uint8_t address2,
  454. uint8_t pinSCL, uint8_t pinSDA, i2c_pullup pullup, uint32_t rate, i2c_op_mode opMode);
  455. //
  456. // Initialize I2C (Master) - initializes I2C as Master mode, external pullups, 100kHz rate,
  457. // and default pin setting
  458. // default pin setting SCL/SDA:
  459. // Wire: 19/18
  460. // Wire1: 29/30 (3.1/3.2), 22/23 (LC), 37/38 (3.5/3.6)
  461. // Wire2: 3/4 (3.5/3.6)
  462. // Wire3: 57/56 (3.6)
  463. // return: none
  464. //
  465. inline void begin(void)
  466. { begin_(i2c, bus, I2C_MASTER, 0, 0, 0, 0, I2C_PULLUP_EXT, 100000, I2C_OP_MODE_ISR); }
  467. //
  468. // Initialize I2C (Slave) - initializes I2C as Slave mode using address, external pullups, 100kHz rate,
  469. // and default pin setting
  470. // default pin setting SCL/SDA:
  471. // Wire: 19/18
  472. // Wire1: 29/30 (3.1/3.2), 22/23 (LC), 37/38 (3.5/3.6)
  473. // Wire2: 3/4 (3.5/3.6)
  474. // Wire3: 57/56 (3.6)
  475. // return: none
  476. // parameters:
  477. // address = 7bit slave address of device
  478. //
  479. inline void begin(int address)
  480. { begin_(i2c, bus, I2C_SLAVE, (uint8_t)address, 0, 0, 0, I2C_PULLUP_EXT, 100000, I2C_OP_MODE_ISR); }
  481. inline void begin(uint8_t address)
  482. { begin_(i2c, bus, I2C_SLAVE, address, 0, 0, 0, I2C_PULLUP_EXT, 100000, I2C_OP_MODE_ISR); }
  483. //
  484. // Initialize I2C - initializes I2C as Master or single address Slave
  485. // return: none
  486. // parameters (optional parameters marked '^'):
  487. // mode = I2C_MASTER, I2C_SLAVE
  488. // address1 = 7bit slave address when configured as Slave (ignored for Master mode)
  489. // ^address2 = 2nd 7bit address for specifying Slave address range (ignored for Master mode)
  490. // ^pins = pins to use, can be specified as 'i2c_pins' enum,
  491. // or as 'SCL,SDA' pair (using any valid SCL or SDA), options are:
  492. // Pin Name
  493. // Interface Devices (deprecated) SCL SDA Default
  494. // --------- ------- -------------- ----- ----- -------
  495. // Wire All I2C_PINS_16_17 16 17
  496. // Wire All I2C_PINS_18_19 19* 18 +
  497. // Wire 3.5/3.6 I2C_PINS_7_8 7 8
  498. // Wire 3.5/3.6 I2C_PINS_33_34 33 34
  499. // Wire 3.5/3.6 I2C_PINS_47_48 47 48
  500. // Wire1 LC I2C_PINS_22_23 22 23 +
  501. // Wire1 3.1/3.2 I2C_PINS_26_31 26 31
  502. // Wire1 3.1/3.2 I2C_PINS_29_30 29 30 +
  503. // Wire1 3.5/3.6 I2C_PINS_37_38 37 38 +
  504. // Wire2 3.5/3.6 I2C_PINS_3_4 3 4 +
  505. // Wire3 3.6 I2C_PINS_56_57 57* 56 +
  506. // (note: in almost all cases SCL is the lower pin #, except cases marked *)
  507. // ^pullup = I2C_PULLUP_EXT, I2C_PULLUP_INT (default I2C_PULLUP_EXT)
  508. // ^rate = I2C frequency to use, can be specified directly in Hz, eg. 400000 for 400kHz, or using one of the
  509. // following enum values (deprecated):
  510. // I2C_RATE_100, I2C_RATE_200, I2C_RATE_300, I2C_RATE_400,
  511. // I2C_RATE_600, I2C_RATE_800, I2C_RATE_1000, I2C_RATE_1200,
  512. // I2C_RATE_1500, I2C_RATE_1800, I2C_RATE_2000, I2C_RATE_2400,
  513. // I2C_RATE_2800, I2C_RATE_3000
  514. // ^opMode = I2C_OP_MODE_IMM, I2C_OP_MODE_ISR, I2C_OP_MODE_DMA (ignored for Slave mode, defaults ISR mode)
  515. //
  516. inline void begin(i2c_mode mode, uint8_t address1, i2c_pins pins=I2C_PINS_DEFAULT,
  517. i2c_pullup pullup=I2C_PULLUP_EXT, uint32_t rate=400000, i2c_op_mode opMode=I2C_OP_MODE_ISR)
  518. { begin_(i2c, bus, mode, address1, 0, mapSCL(pins), mapSDA(pins), pullup, rate, opMode); }
  519. inline void begin(i2c_mode mode, uint8_t address1, uint8_t pinSCL, uint8_t pinSDA,
  520. i2c_pullup pullup=I2C_PULLUP_EXT, uint32_t rate=400000, i2c_op_mode opMode=I2C_OP_MODE_ISR)
  521. { begin_(i2c, bus, mode, address1, 0, pinSCL, pinSDA, pullup, rate, opMode); }
  522. inline void begin(i2c_mode mode, uint8_t address1, uint8_t address2, i2c_pins pins=I2C_PINS_DEFAULT,
  523. i2c_pullup pullup=I2C_PULLUP_EXT, uint32_t rate=400000, i2c_op_mode opMode=I2C_OP_MODE_ISR)
  524. { begin_(i2c, bus, mode, address1, address2, mapSCL(pins), mapSDA(pins), pullup, rate, opMode); }
  525. inline void begin(i2c_mode mode, uint8_t address1, uint8_t address2, uint8_t pinSCL, uint8_t pinSDA,
  526. i2c_pullup pullup=I2C_PULLUP_EXT, uint32_t rate=400000, i2c_op_mode opMode=I2C_OP_MODE_ISR)
  527. { begin_(i2c, bus, mode, address1, address2, pinSCL, pinSDA, pullup, rate, opMode); }
  528. // ------------------------------------------------------------------------------------------------------
  529. // Set Operating Mode (base routine)
  530. //
  531. static uint8_t setOpMode_(struct i2cStruct* i2c, uint8_t bus, i2c_op_mode opMode);
  532. //
  533. // Set Operating Mode - this configures operating mode of the I2C as either Immediate, ISR, or DMA.
  534. // By default Arduino-style begin() calls will initialize to ISR mode. This can
  535. // only be called when the bus is idle (no changing mode in the middle of Tx/Rx).
  536. // Note that Slave mode can only use ISR operation.
  537. // return: 1=success, 0=fail (bus busy)
  538. // parameters:
  539. // opMode = I2C_OP_MODE_ISR, I2C_OP_MODE_DMA, I2C_OP_MODE_IMM
  540. //
  541. inline uint8_t setOpMode(i2c_op_mode opMode) { return setOpMode_(i2c, bus, opMode); }
  542. // ------------------------------------------------------------------------------------------------------
  543. // Set I2C rate (base routine)
  544. //
  545. static void setRate_(struct i2cStruct* i2c, uint32_t busFreq, uint32_t i2cFreq);
  546. //
  547. // Set I2C rate - reconfigures I2C frequency divider based on supplied bus freq and desired I2C freq.
  548. // This will be done assuming an idealized I2C rate, even though at high I2C rates
  549. // the actual throughput is much lower than theoretical value.
  550. //
  551. // Since the division ratios are quantized with non-uniform spacing, the selected rate
  552. // will be the one using the nearest available divider.
  553. // return: none
  554. // parameters:
  555. // busFreq = bus frequency, typically F_BUS unless reconfigured
  556. // freq = desired I2C frequency (will be quantized to nearest rate), or can be I2C_RATE_XXX enum (deprecated),
  557. // such as I2C_RATE_100, I2C_RATE_400, etc...
  558. //
  559. // Max I2C rate is 1/20th F_BUS. Some examples:
  560. //
  561. // F_CPU F_BUS Max I2C
  562. // (MHz) (MHz) Rate
  563. // ------------- ----- ----------
  564. // 240/120 120 6.0M bus overclock
  565. // 216 108 5.4M bus overclock
  566. // 192/96 96 4.8M bus overclock
  567. // 180 90 4.5M bus overclock
  568. // 240 80 4.0M bus overclock
  569. // 216/144/72 72 3.6M bus overclock
  570. // 192 64 3.2M bus overclock
  571. // 240/180/120 60 3.0M
  572. // 168 56 2.8M
  573. // 216 54 2.7M
  574. // 192/144/96/48 48 2.4M
  575. // 72 36 1.8M
  576. // 24 24 1.2M
  577. // 16 16 800k
  578. // 8 8 400k
  579. // 4 4 200k
  580. // 2 2 100k
  581. //
  582. inline void setRate(uint32_t busFreq, uint32_t i2cFreq) { setRate_(i2c, busFreq, i2cFreq); }
  583. // return value and i2c_rate enum no longer needed (deprecated form, always returns 1)
  584. inline uint8_t setRate(uint32_t busFreq, i2c_rate rate) { setRate_(i2c, busFreq, (uint32_t)rate); return 1; }
  585. // Wire compatibility
  586. inline void setClock(uint32_t i2cFreq)
  587. {
  588. #if defined(__MKL26Z64__) // LC
  589. if(i2c->currentSCL == 22)
  590. setRate_(i2c, (uint32_t)F_CPU, i2cFreq); // LC Wire1 bus uses system clock (F_CPU) instead of bus clock (F_BUS)
  591. else
  592. setRate_(i2c, (uint32_t)F_BUS, i2cFreq);
  593. #else
  594. setRate_(i2c, (uint32_t)F_BUS, i2cFreq);
  595. #endif
  596. }
  597. // i2c_t3 version of setClock (deprecated)
  598. inline uint8_t setRate(i2c_rate rate) { setClock((uint32_t)rate); return 1; }
  599. // ------------------------------------------------------------------------------------------------------
  600. // Get I2C clock - return current clock setting
  601. // return: uint32_t = bus frequency (Hz)
  602. // parameters: none
  603. inline uint32_t getClock(void) { return i2c->currentRate; }
  604. // ------------------------------------------------------------------------------------------------------
  605. // Configure I2C pins (base routine)
  606. //
  607. static uint8_t pinConfigure_(struct i2cStruct* i2c, uint8_t bus, uint8_t pinSCL, uint8_t pinSDA, i2c_pullup pullup,
  608. uint8_t configuredSCL, uint8_t configuredSDA);
  609. //
  610. // ------------------------------------------------------------------------------------------------------
  611. // Configure I2C pins - reconfigures active I2C pins on-the-fly (only works when bus is idle). If reconfig
  612. // set then inactive pins will switch to input mode using same pullup configuration.
  613. // return: 1=success, 0=fail (bus busy or incompatible pins)
  614. // parameters:
  615. // pins = pins to use, can be specified as 'i2c_pins' enum,
  616. // or as 'SCL,SDA' pair (using any valid SCL or SDA), options are:
  617. // Pin Name
  618. // Interface Devices (deprecated) SCL SDA Default
  619. // --------- ------- -------------- ----- ----- -------
  620. // Wire All I2C_PINS_16_17 16 17
  621. // Wire All I2C_PINS_18_19 19* 18 +
  622. // Wire 3.5/3.6 I2C_PINS_7_8 7 8
  623. // Wire 3.5/3.6 I2C_PINS_33_34 33 34
  624. // Wire 3.5/3.6 I2C_PINS_47_48 47 48
  625. // Wire1 LC I2C_PINS_22_23 22 23 +
  626. // Wire1 3.1/3.2 I2C_PINS_26_31 26 31
  627. // Wire1 3.1/3.2 I2C_PINS_29_30 29 30 +
  628. // Wire1 3.5/3.6 I2C_PINS_37_38 37 38 +
  629. // Wire2 3.5/3.6 I2C_PINS_3_4 3 4 +
  630. // Wire3 3.6 I2C_PINS_56_57 57* 56 +
  631. // (note: in almost all cases SCL is the lower pin #, except cases marked *)
  632. // ^pullup = I2C_PULLUP_EXT, I2C_PULLUP_INT (default I2C_PULLUP_EXT)
  633. //
  634. inline uint8_t pinConfigure(i2c_pins pins, i2c_pullup pullup=I2C_PULLUP_EXT)
  635. { return pinConfigure_(i2c, bus, mapSCL(pins), mapSDA(pins), pullup, i2c->configuredSCL, i2c->configuredSDA); }
  636. inline uint8_t pinConfigure(uint8_t pinSCL, uint8_t pinSDA, i2c_pullup pullup=I2C_PULLUP_EXT)
  637. { return pinConfigure_(i2c, bus, pinSCL, pinSDA, pullup, i2c->configuredSCL, i2c->configuredSDA); }
  638. //
  639. // ------------------------------------------------------------------------------------------------------
  640. // Set SCL/SDA - change the SCL or SDA pin
  641. // return: none
  642. // parameters:
  643. // pin = pin to use, if invalid then no change will occur
  644. inline void setSCL(uint8_t pin)
  645. { pinConfigure_(i2c, bus, pin, i2c->currentSDA, i2c->currentPullup, i2c->configuredSCL, 1); }
  646. inline void setSDA(uint8_t pin)
  647. { pinConfigure_(i2c, bus, i2c->currentSCL, pin, i2c->currentPullup, 1, i2c->configuredSDA); }
  648. //
  649. // ------------------------------------------------------------------------------------------------------
  650. // Get SCL/SDA - get the current SCL or SDA pin
  651. // return: pin used
  652. //
  653. inline uint8_t getSCL(void) { return i2c->currentSCL; }
  654. inline uint8_t getSDA(void) { return i2c->currentSDA; }
  655. // ------------------------------------------------------------------------------------------------------
  656. // Set Default Timeout - sets the default timeout to be applied to all functions called with a timeout of
  657. // zero (the default in cases where timeout is not specified). The default is
  658. // initially zero (infinite wait).
  659. // return: none
  660. // parameters:
  661. // timeout = timeout in microseconds
  662. inline void setDefaultTimeout(uint32_t timeout) { i2c->defTimeout = timeout; }
  663. // ------------------------------------------------------------------------------------------------------
  664. // Acquire Bus - acquires bus in Master mode and escalates priority as needed, intended
  665. // for internal use only
  666. // return: 1=success, 0=fail (cannot acquire bus)
  667. // parameters:
  668. // timeout = timeout in microseconds
  669. // forceImm = flag to indicate if immediate mode is required
  670. //
  671. static uint8_t acquireBus_(struct i2cStruct* i2c, uint8_t bus, uint32_t timeout, uint8_t& forceImm);
  672. // ------------------------------------------------------------------------------------------------------
  673. // Reset Bus - toggles SCL until SDA line is released (9 clocks max). This is used to correct
  674. // a hung bus in which a Slave device missed some clocks and remains stuck outputting
  675. // a low signal on SDA (thereby preventing START/STOP signaling).
  676. // return: none
  677. //
  678. static void resetBus_(struct i2cStruct* i2c, uint8_t bus);
  679. inline void resetBus(void) { resetBus_(i2c, bus); }
  680. // ------------------------------------------------------------------------------------------------------
  681. // Setup Master Transmit - initialize Tx buffer for transmit to slave at address
  682. // return: none
  683. // parameters:
  684. // address = target 7bit slave address
  685. //
  686. void beginTransmission(uint8_t address);
  687. inline void beginTransmission(int address) { beginTransmission((uint8_t)address); } // Wire compatibility
  688. // ------------------------------------------------------------------------------------------------------
  689. // Master Transmit (base routine) - cannot be static due to call to getError() and in turn getWriteError()
  690. //
  691. uint8_t endTransmission(struct i2cStruct* i2c, uint8_t bus, i2c_stop sendStop, uint32_t timeout);
  692. //
  693. // Master Transmit - blocking routine, transmits Tx buffer to slave. i2c_stop parameter can be used
  694. // to indicate if command should end with a STOP(I2C_STOP) or not (I2C_NOSTOP).
  695. // Timeout parameter can be optionally specified.
  696. // return: 0=success, 1=data too long, 2=recv addr NACK, 3=recv data NACK, 4=other error
  697. // parameters:
  698. // ^i2c_stop = I2C_NOSTOP, I2C_STOP (default STOP)
  699. // ^timeout = timeout in microseconds (default 0 = infinite wait)
  700. //
  701. inline uint8_t endTransmission(i2c_stop sendStop=I2C_STOP, uint32_t timeout=0) { return endTransmission(i2c, bus, sendStop, timeout); }
  702. inline uint8_t endTransmission(uint8_t sendStop) { return endTransmission(i2c, bus, (i2c_stop)sendStop, 0); } // Wire compatibility
  703. // ------------------------------------------------------------------------------------------------------
  704. // Send Master Transmit (base routine)
  705. //
  706. static void sendTransmission_(struct i2cStruct* i2c, uint8_t bus, i2c_stop sendStop, uint32_t timeout);
  707. //
  708. // Send Master Transmit - non-blocking routine, starts transmit of Tx buffer to slave. i2c_stop parameter can be
  709. // used to indicate if command should end with a STOP (I2C_STOP) or not (I2C_NOSTOP). Use
  710. // done(), finish(), or onTransmitDone() callback to determine completion and
  711. // status() to determine success/fail. Note that sendTransmission() does not currently
  712. // support timeouts (aside from initial bus acquisition which does support it).
  713. // return: none
  714. // parameters:
  715. // ^i2c_stop = I2C_NOSTOP, I2C_STOP (default STOP)
  716. //
  717. inline void sendTransmission(i2c_stop sendStop=I2C_STOP) { sendTransmission_(i2c, bus, sendStop, 0); }
  718. // ------------------------------------------------------------------------------------------------------
  719. // Master Receive (base routine)
  720. //
  721. static size_t requestFrom_(struct i2cStruct* i2c, uint8_t bus, uint8_t addr, size_t len, i2c_stop sendStop, uint32_t timeout);
  722. //
  723. // Master Receive - Requests length bytes from slave at address. Receive data will be placed in the Rx buffer.
  724. // i2c_stop parameter can be used to indicate if command should end with a STOP (I2C_STOP) or
  725. // not (I2C_NOSTOP). Timeout parameter can be optionally specified.
  726. // return: #bytes received = success, 0=fail (0 length request, NAK, timeout, or bus error)
  727. // parameters:
  728. // address = target 7bit slave address
  729. // length = number of bytes requested
  730. // ^i2c_stop = I2C_NOSTOP, I2C_STOP (default STOP)
  731. // ^timeout = timeout in microseconds (default 0 = infinite wait)
  732. //
  733. inline size_t requestFrom(uint8_t addr, size_t len, i2c_stop sendStop=I2C_STOP, uint32_t timeout=0)
  734. { return requestFrom_(i2c, bus, addr, len, sendStop, timeout); }
  735. inline size_t requestFrom(int addr, int len)
  736. { return requestFrom_(i2c, bus, (uint8_t)addr, (size_t)len, I2C_STOP, 0); } // Wire compatibility
  737. inline uint8_t requestFrom(uint8_t addr, uint8_t len, uint8_t sendStop=1)
  738. { return (uint8_t)requestFrom_(i2c, bus, addr, (size_t)len, (i2c_stop)sendStop, 0); } // Wire compatibility
  739. // ------------------------------------------------------------------------------------------------------
  740. // Start Master Receive (base routine)
  741. //
  742. static void sendRequest_(struct i2cStruct* i2c, uint8_t bus, uint8_t addr, size_t len, i2c_stop sendStop, uint32_t timeout);
  743. //
  744. // Start Master Receive - non-blocking routine, starts request for length bytes from slave at address. Receive
  745. // data will be placed in the Rx buffer. i2c_stop parameter can be used to indicate if
  746. // command should end with a STOP (I2C_STOP) or not (I2C_NOSTOP). Use done(), finish()
  747. // or onReqFromDone() callback to determine completion and status() to determine
  748. // success/fail.
  749. // return: none
  750. // parameters:
  751. // address = target 7bit slave address
  752. // length = number of bytes requested
  753. // ^i2c_stop = I2C_NOSTOP, I2C_STOP (default STOP)
  754. //
  755. inline void sendRequest(uint8_t addr, size_t len, i2c_stop sendStop=I2C_STOP) { sendRequest_(i2c, bus, addr, len, sendStop, 0); }
  756. // ------------------------------------------------------------------------------------------------------
  757. // Get Wire Error - returns "Wire" error code from a failed Tx/Rx command
  758. // return: 0=success, 1=data too long, 2=recv addr NACK, 3=recv data NACK, 4=other error
  759. //
  760. uint8_t getError(void);
  761. // ------------------------------------------------------------------------------------------------------
  762. // Return Status - returns current status of I2C (enum return value)
  763. // return: I2C_WAITING, I2C_TIMEOUT, I2C_ADDR_NAK, I2C_DATA_NAK, I2C_ARB_LOST, I2C_BUF_OVF,
  764. // I2C_NOT_ACQ, I2C_DMA_ERR, I2C_SENDING, I2C_SEND_ADDR, I2C_RECEIVING, I2C_SLAVE_TX, I2C_SLAVE_RX
  765. //
  766. inline i2c_status status(void) { return i2c->currentStatus; }
  767. // ------------------------------------------------------------------------------------------------------
  768. // Return Status (base routine)
  769. //
  770. static uint8_t done_(struct i2cStruct* i2c);
  771. //
  772. // Done Check - returns simple complete/not-complete value to indicate I2C status
  773. // return: 1=Tx/Rx complete (with or without errors), 0=still running
  774. //
  775. inline uint8_t done(void) { return done_(i2c); }
  776. // ------------------------------------------------------------------------------------------------------
  777. // Return Status (base routine)
  778. //
  779. static uint8_t finish_(struct i2cStruct* i2c, uint8_t bus, uint32_t timeout);
  780. //
  781. // Finish - blocking routine, loops until Tx/Rx is complete. Timeout parameter can be optionally specified.
  782. // return: 1=success (Tx or Rx completed, no error), 0=fail (NAK, timeout or Arb Lost)
  783. // parameters:
  784. // ^timeout = timeout in microseconds (default 0 = infinite wait)
  785. //
  786. inline uint8_t finish(uint32_t timeout=0) { return finish_(i2c, bus, timeout); }
  787. // ------------------------------------------------------------------------------------------------------
  788. // Write - write data byte to Tx buffer
  789. // return: #bytes written = success, 0=fail
  790. // parameters:
  791. // data = data byte
  792. //
  793. size_t write(uint8_t data);
  794. inline size_t write(unsigned long n) { return write((uint8_t)n); }
  795. inline size_t write(long n) { return write((uint8_t)n); }
  796. inline size_t write(unsigned int n) { return write((uint8_t)n); }
  797. inline size_t write(int n) { return write((uint8_t)n); }
  798. // ------------------------------------------------------------------------------------------------------
  799. // Write Array - write count number of bytes from data array to Tx buffer
  800. // return: #bytes written = success, 0=fail
  801. // parameters:
  802. // data = pointer to uint8_t (or char) array of data
  803. // count = number of bytes to write
  804. //
  805. // As a special case C-strings (null terminated) can be written without a count byte
  806. //
  807. size_t write(const uint8_t* data, size_t count);
  808. inline size_t write(const char* str, size_t count) { return write((const uint8_t*)str, count); }
  809. inline size_t write(const char* str) { return write((const uint8_t*)str, strlen(str)+1); } // write C-string
  810. // ------------------------------------------------------------------------------------------------------
  811. // Available - returns number of remaining available bytes in Rx buffer
  812. // return: #bytes available
  813. //
  814. inline int available(void) { return i2c->rxBufferLength - i2c->rxBufferIndex; }
  815. // ------------------------------------------------------------------------------------------------------
  816. // Read (base routine)
  817. //
  818. static int read_(struct i2cStruct* i2c);
  819. //
  820. // Read - returns next data byte (signed int) from Rx buffer
  821. // return: data, -1 if buffer empty
  822. //
  823. inline int read(void) { return read_(i2c); }
  824. // ------------------------------------------------------------------------------------------------------
  825. // Read Array - read count number of bytes from Rx buffer to data array
  826. // return: #bytes read
  827. // parameters:
  828. // data = pointer to uint8_t (or char) array of data
  829. // count = number of bytes to read
  830. //
  831. static size_t read_(struct i2cStruct* i2c, uint8_t* data, size_t count);
  832. inline size_t read(uint8_t* data, size_t count) { return read_(i2c, data, count); }
  833. inline size_t read(char* str, size_t count) { return read_(i2c, (uint8_t*)str, count); }
  834. // ------------------------------------------------------------------------------------------------------
  835. // Peek (base routine)
  836. //
  837. static int peek_(struct i2cStruct* i2c);
  838. //
  839. // Peek - returns next data byte (signed int) from Rx buffer without removing it from Rx buffer
  840. // return: data, -1 if buffer empty
  841. //
  842. inline int peek(void) { return peek_(i2c); }
  843. // ------------------------------------------------------------------------------------------------------
  844. // Read Byte (base routine)
  845. //
  846. static uint8_t readByte_(struct i2cStruct* i2c);
  847. //
  848. // Read Byte - returns next data byte (uint8_t) from Rx buffer
  849. // return: data, 0 if buffer empty
  850. //
  851. inline uint8_t readByte(void) { return readByte_(i2c); }
  852. // ------------------------------------------------------------------------------------------------------
  853. // Peek Byte (base routine)
  854. //
  855. static uint8_t peekByte_(struct i2cStruct* i2c);
  856. //
  857. // Peek Byte - returns next data byte (uint8_t) from Rx buffer without removing it from Rx buffer
  858. // return: data, 0 if buffer empty
  859. //
  860. inline uint8_t peekByte(void) { return peekByte_(i2c); }
  861. // ------------------------------------------------------------------------------------------------------
  862. // Flush (not implemented)
  863. //
  864. inline void flush(void) {}
  865. // ------------------------------------------------------------------------------------------------------
  866. // Get Rx Address - returns target address of incoming I2C command. Used for Slaves operating over an address range.
  867. // return: rxAddr of last received command
  868. //
  869. inline uint8_t getRxAddr(void) { return i2c->rxAddr; }
  870. // ------------------------------------------------------------------------------------------------------
  871. // Set callback function for Master Tx
  872. //
  873. inline void onTransmitDone(void (*function)(void)) { i2c->user_onTransmitDone = function; }
  874. // ------------------------------------------------------------------------------------------------------
  875. // Set callback function for Master Rx
  876. //
  877. inline void onReqFromDone(void (*function)(void)) { i2c->user_onReqFromDone = function; }
  878. // ------------------------------------------------------------------------------------------------------
  879. // Set callback function for Slave Rx
  880. //
  881. inline void onReceive(void (*function)(size_t len)) { i2c->user_onReceive = function; }
  882. // ------------------------------------------------------------------------------------------------------
  883. // Set callback function for Slave Tx
  884. //
  885. inline void onRequest(void (*function)(void)) { i2c->user_onRequest = function; }
  886. // ------------------------------------------------------------------------------------------------------
  887. // Set callback function for Errors
  888. //
  889. inline void onError(void (*function)(void)) { i2c->user_onError = function; }
  890. // ------------------------------------------------------------------------------------------------------
  891. // Get error count from specified counter
  892. // return: error count
  893. // parameters:
  894. // counter = I2C_ERRCNT_RESET_BUS, I2C_ERRCNT_TIMEOUT, I2C_ERRCNT_ADDR_NAK, I2C_ERRCNT_DATA_NAK,
  895. // I2C_ERRCNT_ARBL, I2C_ERRCNT_NOT_ACQ, I2C_ERRCNT_DMA_ERR
  896. //
  897. inline uint32_t getErrorCount(i2c_err_count counter) { return i2c->errCounts[counter]; }
  898. // ------------------------------------------------------------------------------------------------------
  899. // Zero error count of specified counter
  900. // return: none
  901. // parameters:
  902. // counter = I2C_ERRCNT_RESET_BUS, I2C_ERRCNT_TIMEOUT, I2C_ERRCNT_ADDR_NAK, I2C_ERRCNT_DATA_NAK,
  903. // I2C_ERRCNT_ARBL, I2C_ERRCNT_NOT_ACQ, I2C_ERRCNT_DMA_ERR
  904. //
  905. inline void zeroErrorCount(i2c_err_count counter) { i2c->errCounts[counter] = 0; }
  906. // ------------------------------------------------------------------------------------------------------
  907. // For compatibility with pre-1.0 sketches and libraries
  908. inline void send(uint8_t b) { write(b); }
  909. inline void send(uint8_t* s, uint8_t n) { write(s, n); }
  910. inline void send(int n) { write((uint8_t)n); }
  911. inline void send(char* s) { write(s); }
  912. inline uint8_t receive(void) { int c = read(); return (c<0) ? 0 : c; }
  913. };
  914. extern i2c_t3 Wire;
  915. #if I2C_BUS_NUM >= 2
  916. extern i2c_t3 Wire1;
  917. #endif
  918. #if I2C_BUS_NUM >= 3
  919. extern i2c_t3 Wire2;
  920. #endif
  921. #if I2C_BUS_NUM >= 4
  922. extern i2c_t3 Wire3;
  923. #endif
  924. #endif // I2C_T3_H
  925. /*
  926. ------------------------------------------------------------------------------------------------------
  927. Changelog
  928. ------------------------------------------------------------------------------------------------------
  929. - (v11.0) Modified 01Dec18 by Brian (nox771 at gmail.com)
  930. - Added state variables and modified pinConfigure_() to recognize unconfigured SCL/SDA pins,
  931. allowing for setSCL()/setSDA() prior to begin(), which was previously blocked by bus busy
  932. check on unconfigured pins.
  933. - Header change to MIT permissive license
  934. - (v10.1) Modified 02Jan18 by Brian (nox771 at gmail.com)
  935. - Added User #define to disable priority checks entirely
  936. - Added i2c_t3::isrActive flag to dynamically disable priority checks during ISR & callbacks.
  937. This is to prevent runaway priority escalation in cases of callbacks with nested Wire calls.
  938. - (v10.0) Modified 21Oct17 by Brian (nox771 at gmail.com)
  939. - Default assignments have been added to many functions for pins/pullup/rate/op_mode, so
  940. all those parameters are now optional in many function calls (marked ^ below)
  941. - Unbound SCL/SDA pin assignment. Pins can be specified with either i2c_pins enum or by direct
  942. SCL,SDA pin definition (using any valid SCL and SDA pin). New function summary is:
  943. - begin(mode, address1, ^i2c_pins, ^i2c_pullup, ^rate, ^i2c_op_mode)
  944. - begin(mode, address1, ^pinSCL, ^pinSDA, ^i2c_pullup, ^rate, ^i2c_op_mode)
  945. - pinConfigure(i2c_pins, ^pullup)
  946. - pinConfigure(pinSCL, pinSDA, ^pullup)
  947. - setSCL(pin)
  948. - setSDA(pin)
  949. - getSCL()
  950. - getSDA()
  951. Note: internal to i2c structure, currentPins has been replaced by currentSCL and currentSDA
  952. - Added Master callback functions for completion of transfers. Primarily for
  953. sendTransmission/sendRequest, but these will also work on foreground commands
  954. endTransmission/requestFrom. Also added an Error callback for Master bus errors.
  955. - onTransmitDone(function) - where function() is called when Master Transmit is complete
  956. - onReqFromDone(function) - where function() is called when Master Receive is complete
  957. - onError(function) - where function() is called upon any I2C error which terminates the
  958. Master bus operation (eg. NAK, timeout, acquire fail, etc)
  959. - Fixed blocking conditions that could occur in immediate mode
  960. - Added error counters which may be optionally enabled via I2C_ERROR_COUNTERS define. When
  961. enabled it will track (Master mode only): Reset Bus (auto-retry only), Timeout, Addr NAK,
  962. Data NAK, Arb Lost, Bus Not Acquired, DMA Errors.
  963. - i2c_err_count enum, getErrorCount(), and zeroErrorCount() functions added
  964. - (v9.4) Modified 01Oct17 by Brian (nox771 at gmail.com)
  965. - Fixed Slave ISR for LC/3.5/3.6 not properly recognizing RepSTART
  966. - Fixed nested Wire calls during Slave ISR receive (calling Wire inside Wire1 Slave ISR)
  967. - Added uint8_t and char array read functions - Wire.read(databuf, count);
  968. - (v9.3) Modified 20Sep17 by Brian (nox771 at gmail.com)
  969. - Fixed Slave ISR for LC/3.5/3.6
  970. - (v9.2) Modified 29Dec16 by Brian (nox771 at gmail.com)
  971. - improved resetBus() function to reset C1 state (thanks hw999)
  972. - (v9.1) Modified 16Oct16 by Brian (nox771 at gmail.com)
  973. - applied two fixes due to bug reports:
  974. - removed I2C_F_DIV120 setting (120 divide-ratio) for I2C clock
  975. - disabled I2C_AUTO_RETRY by default (setting remains but must be manually enabled)
  976. - (v9) Modified 01Jul16 by Brian (nox771 at gmail.com)
  977. - Added support for Teensy 3.5/3.6:
  978. - fully supported (Master/Slave modes, IMM/ISR/DMA operation)
  979. - supports all available pin/bus options on Wire/Wire1/Wire2/Wire3
  980. - Fixed LC slave bug, whereby it was incorrectly detecting STOPs directed to other slaves
  981. - I2C rate is now set using a much more flexible method than previously used (this is partially
  982. motivated by increasing device count and frequencies). As a result, the fixed set of rate
  983. enums are no longer needed (however they are currently still supported), and desired I2C
  984. frequency can be directly specified, eg. for 400kHz, I2C_RATE_400 can be replaced by 400000.
  985. Some setRate() functions are deprecated due to these changes.
  986. - (v8) Modified 02Apr15 by Brian (nox771 at gmail.com)
  987. - added support for Teensy LC:
  988. - fully supported (Master/Slave modes, IMM/ISR/DMA operation)
  989. - Wire: pins 16/17 or 18/19, rate limited to I2C_RATE_1200
  990. - Wire1: pins 22/23, rate limited to I2C_RATE_2400
  991. - added timeout on acquiring bus (prevents lockup when bus cannot be acquired)
  992. - added setDefaultTimeout() function for setting the default timeout to apply to all commands
  993. - added resetBus() function for toggling SCL to release stuck Slave devices
  994. - added setRate(rate) function, similar to setClock(freq), but using rate specifiers (does not
  995. require specifying busFreq)
  996. - added I2C_AUTO_RETRY user define
  997. - (v7) Modified 09Jan15 by Brian (nox771 at gmail.com)
  998. - added support for F_BUS frequencies: 60MHz, 56MHz, 48MHz, 36MHz, 24MHz, 16MHz, 8MHz, 4MHz, 2MHz
  999. - added new rates: I2C_RATE_1800, I2C_RATE_2800, I2C_RATE_3000
  1000. - added new priority escalation - in cases where I2C ISR is blocked by having a lower priority than
  1001. calling function, the I2C will either adjust I2C ISR to a higher priority,
  1002. or switch to Immediate mode as needed.
  1003. - added new operating mode control - I2C can be set to operate in ISR mode, DMA mode (Master only),
  1004. or Immediate Mode (Master only)
  1005. - added new begin() functions to allow setting the initial operating mode:
  1006. - begin(i2c_mode mode, uint8_t address, i2c_pins pins, i2c_pullup pullup, i2c_rate rate, i2c_op_mode opMode)
  1007. - begin(i2c_mode mode, uint8_t address1, uint8_t address2, i2c_pins pins, i2c_pullup pullup, i2c_rate rate, i2c_op_mode opMode)
  1008. - added new functions:
  1009. - uint8_t setOpMode(i2c_op_mode opMode) - used to change operating mode on the fly (only when bus is idle)
  1010. - void sendTransmission() - non-blocking Tx with implicit I2C_STOP, added for symmetry with endTransmission()
  1011. - uint8_t setRate(uint32_t busFreq, i2c_rate rate) - used to set I2C clock dividers to get desired rate, i2c_rate argument
  1012. - uint8_t setRate(uint32_t busFreq, uint32_t i2cFreq) - used to set I2C clock dividers to get desired SCL freq, uint32_t argument
  1013. (quantized to nearest i2c_rate)
  1014. - added new Wire compatibility functions:
  1015. - void setClock(uint32_t i2cFreq) - (note: degenerate form of setRate() with busFreq == F_BUS)
  1016. - uint8_t endTransmission(uint8_t sendStop)
  1017. - uint8_t requestFrom(uint8_t addr, uint8_t len)
  1018. - uint8_t requestFrom(uint8_t addr, uint8_t len, uint8_t sendStop)
  1019. - fixed bug in Slave Range code whereby onRequest() callback occurred prior to updating rxAddr instead of after
  1020. - fixed bug in arbitration, was missing from Master Tx mode
  1021. - removed I2C1 defines (now included in kinetis.h)
  1022. - removed all debug code (eliminates rbuf dependency)
  1023. - (v6) Modified 16Jan14 by Brian (nox771 at gmail.com)
  1024. - all new structure using dereferenced pointers instead of hardcoding. This allows functions
  1025. (including ISRs) to be reused across multiple I2C buses. Most functions moved to static,
  1026. which in turn are called by inline user functions. Added new struct (i2cData) for holding all
  1027. bus information.
  1028. - added support for Teensy 3.1 and I2C1 interface on pins 29/30 and 26/31.
  1029. - added header define (I2C_BUS_ENABLE n) to control number of enabled buses (eg. both I2C0 & I2C1
  1030. or just I2C0). When using only I2C0 the code and ram usage will be lower.
  1031. - added interrupt flag (toggles pin high during ISR) with independent defines for I2C0 and
  1032. I2C1 (refer to header file), useful for logic analyzer trigger
  1033. - (v5) Modified 09Jun13 by Brian (nox771 at gmail.com)
  1034. - fixed bug in ISR timeout code in which timeout condition could fail to reset in certain cases
  1035. - fixed bug in Slave mode in sda_rising_isr attach, whereby it was not getting attached on the addr byte
  1036. - moved debug routines so they are entirely defined internal to the library (no end user code req'd)
  1037. - debug routines now use IntervalTimer library
  1038. - added support for range of Slave addresses
  1039. - added getRxAddr() for Slave using addr range to determine its called address
  1040. - removed virtual keyword from all functions (is not a base class)
  1041. - (v1-v4) Modified 26Feb13 by Brian (nox771 at gmail.com)
  1042. - Reworked begin function:
  1043. - added option for pins to use (SCL:SDA on 19:18 or 16:17 - note pin order difference)
  1044. - added option for internal pullup - as mentioned in previous code pullup is very strong,
  1045. approx 190 ohms, but is possibly useful for high speed I2C
  1046. - added option for rates - 100kHz, 200kHz, 300kHz, 400kHz, 600kHz, 800kHz, 1MHz, 1.2MHz, <-- 24/48MHz bus
  1047. 1.5MHz, 2.0MHz, 2.4MHz <-- 48MHz bus only
  1048. - Removed string.h dependency (memcpy)
  1049. - Changed Master modes to interrupt driven
  1050. - Added non-blocking Tx/Rx routines, and status/done/finish routines:
  1051. - sendTransmission() - non-blocking transmit
  1052. - sendRequest() - non-blocking receive
  1053. - status() - reports current status
  1054. - done() - indicates Tx/Rx complete (for main loop polling if I2C is running in background)
  1055. - finish() - loops until Tx/Rx complete or bus error
  1056. - Added readByte()/peekByte() for uint8_t return values (note: returns 0 instead of -1 if buf empty)
  1057. - Added fixes for Slave Rx mode - in short Slave Rx on this part is fubar
  1058. (as proof, notice the difference in the I2Cx_FLT register in the KL25 Sub-Family parts)
  1059. - the SDA-rising ISR hack can work but only detects STOP conditons.
  1060. A slave Rx followed by RepSTART won't be detected since bus remains busy.
  1061. To fix this if IAAS occurs while already in Slave Rx mode then it will
  1062. assume RepSTART occurred and trigger onReceive callback.
  1063. - Separated Tx/Rx buffer sizes for asymmetric devices (adjustable in i2c_t3.h)
  1064. - Changed Tx/Rx buffer indicies to size_t to allow for large (>256 byte) buffers
  1065. - Left debug routines in place (controlled via header defines - default is OFF). If debug is
  1066. enabled, note that it can easily overrun the Debug queue on large I2C transfers, yielding
  1067. garbage output. Adjust ringbuf size (in rbuf.h) and possibly PIT interrupt rate to adjust
  1068. data flow to Serial (note also the buffer in Serial can overflow if written too quickly).
  1069. - Added getError() function to return Wire error code
  1070. - Added pinConfigure() function for changing pins on the fly (only when bus not busy)
  1071. - Added timeouts to endTransmission(), requestFrom(), and finish()
  1072. ------------------------------------------------------------------------------------------------------
  1073. */