PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1840 lines
82KB

  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(__MK20DX128__) || defined(__MK20DX256__) || defined(__MKL26Z64__) || \
  23. defined(__MK64FX512__) || defined(__MK66FX1M0__) // 3.0/3.1-3.2/LC/3.5/3.6
  24. #include "i2c_t3.h"
  25. // ------------------------------------------------------------------------------------------------------
  26. // Static inits
  27. //
  28. #define I2C_STRUCT(a1,f,c1,s,d,c2,flt,ra,smb,a2,slth,sltl,scl,sda) \
  29. {a1, f, c1, s, d, c2, flt, ra, smb, a2, slth, sltl, {}, 0, 0, {}, 0, 0, I2C_OP_MODE_ISR, I2C_MASTER, scl, sda, I2C_PULLUP_EXT, 100000, \
  30. I2C_STOP, I2C_WAITING, 0, 0, 0, 0, I2C_DMA_OFF, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, {}, 0, 0 }
  31. struct i2cStruct i2c_t3::i2cData[] =
  32. {
  33. I2C_STRUCT(&I2C0_A1, &I2C0_F, &I2C0_C1, &I2C0_S, &I2C0_D, &I2C0_C2, &I2C0_FLT, &I2C0_RA, &I2C0_SMB, &I2C0_A2, &I2C0_SLTH, &I2C0_SLTL, 19, 18)
  34. #if (I2C_BUS_NUM >= 2) && defined(__MK20DX256__) // 3.1/3.2
  35. ,I2C_STRUCT(&I2C1_A1, &I2C1_F, &I2C1_C1, &I2C1_S, &I2C1_D, &I2C1_C2, &I2C1_FLT, &I2C1_RA, &I2C1_SMB, &I2C1_A2, &I2C1_SLTH, &I2C1_SLTL, 29, 30)
  36. #elif (I2C_BUS_NUM >= 2) && defined(__MKL26Z64__) // LC
  37. ,I2C_STRUCT(&I2C1_A1, &I2C1_F, &I2C1_C1, &I2C1_S, &I2C1_D, &I2C1_C2, &I2C1_FLT, &I2C1_RA, &I2C1_SMB, &I2C1_A2, &I2C1_SLTH, &I2C1_SLTL, 22, 23)
  38. #elif (I2C_BUS_NUM >= 2) && (defined(__MK64FX512__) || defined(__MK66FX1M0__)) // 3.5/3.6
  39. ,I2C_STRUCT(&I2C1_A1, &I2C1_F, &I2C1_C1, &I2C1_S, &I2C1_D, &I2C1_C2, &I2C1_FLT, &I2C1_RA, &I2C1_SMB, &I2C1_A2, &I2C1_SLTH, &I2C1_SLTL, 37, 38)
  40. #endif
  41. #if (I2C_BUS_NUM >= 3) && (defined(__MK64FX512__) || defined(__MK66FX1M0__)) // 3.5/3.6
  42. ,I2C_STRUCT(&I2C2_A1, &I2C2_F, &I2C2_C1, &I2C2_S, &I2C2_D, &I2C2_C2, &I2C2_FLT, &I2C2_RA, &I2C2_SMB, &I2C2_A2, &I2C2_SLTH, &I2C2_SLTL, 3, 4)
  43. #endif
  44. #if (I2C_BUS_NUM >= 4) && defined(__MK66FX1M0__) // 3.6
  45. ,I2C_STRUCT(&I2C3_A1, &I2C3_F, &I2C3_C1, &I2C3_S, &I2C3_D, &I2C3_C2, &I2C3_FLT, &I2C3_RA, &I2C3_SMB, &I2C3_A2, &I2C3_SLTH, &I2C3_SLTL, 57, 56)
  46. #endif
  47. };
  48. volatile uint8_t i2c_t3::isrActive = 0;
  49. // ------------------------------------------------------------------------------------------------------
  50. // Constructor/Destructor
  51. //
  52. i2c_t3::i2c_t3(uint8_t i2c_bus)
  53. {
  54. bus = i2c_bus;
  55. i2c = &i2cData[bus];
  56. }
  57. i2c_t3::~i2c_t3()
  58. {
  59. // if DMA active, delete DMA object
  60. if(i2c->opMode == I2C_OP_MODE_DMA)
  61. delete i2c->DMA;
  62. }
  63. // ------------------------------------------------------------------------------------------------------
  64. // Initialize I2C - initializes I2C as Master or address range Slave
  65. // return: none
  66. // parameters (optional parameters marked '^'):
  67. // mode = I2C_MASTER, I2C_SLAVE
  68. // address1 = 7bit slave address when configured as Slave (ignored for Master mode)
  69. // ^ address2 = 2nd 7bit address for specifying Slave address range (ignored for Master mode)
  70. // ^ pins = pins to use, can be specified as 'i2c_pins' enum,
  71. // or as 'SCL,SDA' pair (using any valid SCL or SDA), options are:
  72. // Pin Name
  73. // Interface Devices (deprecated) SCL SDA
  74. // --------- ------- -------------- ----- ----- (note: in almost all cases SCL is the
  75. // Wire All I2C_PINS_16_17 16 17 lower pin #, except cases marked *)
  76. // Wire All I2C_PINS_18_19 19 18 *
  77. // Wire 3.5/3.6 I2C_PINS_7_8 7 8
  78. // Wire 3.5/3.6 I2C_PINS_33_34 33 34
  79. // Wire 3.5/3.6 I2C_PINS_47_48 47 48
  80. // Wire1 LC I2C_PINS_22_23 22 23
  81. // Wire1 3.1/3.2 I2C_PINS_26_31 26 31
  82. // Wire1 3.1/3.2 I2C_PINS_29_30 29 30
  83. // Wire1 3.5/3.6 I2C_PINS_37_38 37 38
  84. // Wire2 3.5/3.6 I2C_PINS_3_4 3 4
  85. // Wire3 3.6 I2C_PINS_56_57 57 56 *
  86. // ^ pullup = I2C_PULLUP_EXT, I2C_PULLUP_INT
  87. // ^ rate = I2C frequency to use, can be specified directly in Hz, eg. 400000 for 400kHz, or using one of the
  88. // following enum values (deprecated):
  89. // I2C_RATE_100, I2C_RATE_200, I2C_RATE_300, I2C_RATE_400,
  90. // I2C_RATE_600, I2C_RATE_800, I2C_RATE_1000, I2C_RATE_1200,
  91. // I2C_RATE_1500, I2C_RATE_1800, I2C_RATE_2000, I2C_RATE_2400,
  92. // I2C_RATE_2800, I2C_RATE_3000
  93. // ^ opMode = I2C_OP_MODE_IMM, I2C_OP_MODE_ISR, I2C_OP_MODE_DMA (ignored for Slave mode, defaults to ISR)
  94. //
  95. void i2c_t3::begin_(struct i2cStruct* i2c, uint8_t bus, i2c_mode mode, uint8_t address1, uint8_t address2,
  96. uint8_t pinSCL, uint8_t pinSDA, i2c_pullup pullup, uint32_t rate, i2c_op_mode opMode)
  97. {
  98. // Enable I2C internal clock
  99. if(bus == 0)
  100. SIM_SCGC4 |= SIM_SCGC4_I2C0;
  101. #if I2C_BUS_NUM >= 2
  102. if(bus == 1)
  103. SIM_SCGC4 |= SIM_SCGC4_I2C1;
  104. #endif
  105. #if I2C_BUS_NUM >= 3
  106. if(bus == 2)
  107. SIM_SCGC1 |= SIM_SCGC1_I2C2;
  108. #endif
  109. #if I2C_BUS_NUM >= 4
  110. if(bus == 3)
  111. SIM_SCGC1 |= SIM_SCGC1_I2C3;
  112. #endif
  113. i2c->currentMode = mode; // Set mode
  114. i2c->currentStatus = I2C_WAITING; // reset status
  115. // Set Master/Slave address
  116. if(i2c->currentMode == I2C_MASTER)
  117. {
  118. *(i2c->C2) = I2C_C2_HDRS; // Set high drive select
  119. //*(i2c->A1) = 0;
  120. //*(i2c->RA) = 0;
  121. }
  122. else
  123. {
  124. *(i2c->C2) = (address2) ? (I2C_C2_HDRS|I2C_C2_RMEN) // Set high drive select and range-match enable
  125. : I2C_C2_HDRS; // Set high drive select
  126. // set Slave address, if two addresses are given, setup range and put lower address in A1, higher in RA
  127. *(i2c->A1) = (address2) ? ((address1 < address2) ? (address1<<1) : (address2<<1))
  128. : (address1<<1);
  129. *(i2c->RA) = (address2) ? ((address1 < address2) ? (address2<<1) : (address1<<1))
  130. : 0;
  131. }
  132. // Setup pins - As noted in original TwoWire.cpp, internal 3.0/3.1/3.2 pullup is strong (about 190 ohms),
  133. // but it can work if other devices on bus have strong enough pulldowns.
  134. //
  135. if(!pinSCL) pinSCL = i2c->currentSCL; // if either pin specified as 0, then use current settings
  136. if(!pinSDA) pinSDA = i2c->currentSDA;
  137. pinConfigure_(i2c, bus, pinSCL, pinSDA, pullup, i2c->configuredSCL, i2c->configuredSDA);
  138. // Set I2C rate
  139. #if defined(__MKL26Z64__) // LC
  140. if(bus == 1)
  141. setRate_(i2c, (uint32_t)F_CPU, rate); // LC Wire1 bus uses system clock (F_CPU) instead of bus clock (F_BUS)
  142. else
  143. setRate_(i2c, (uint32_t)F_BUS, rate);
  144. #else
  145. setRate_(i2c, (uint32_t)F_BUS, rate);
  146. #endif
  147. // Set config registers and operating mode
  148. setOpMode_(i2c, bus, opMode);
  149. if(i2c->currentMode == I2C_MASTER)
  150. *(i2c->C1) = I2C_C1_IICEN; // Master - enable I2C (hold in Rx mode, intr disabled)
  151. else
  152. *(i2c->C1) = I2C_C1_IICEN|I2C_C1_IICIE; // Slave - enable I2C and interrupts
  153. }
  154. // ------------------------------------------------------------------------------------------------------
  155. // Valid pin checks - verify if SCL or SDA pin is valid on given bus, intended for internal use only
  156. // return: alt setting, 0=not valid
  157. // parameters:
  158. // bus = bus number
  159. // pin = pin number to check
  160. // offset = array offset
  161. //
  162. uint8_t i2c_t3::validPin_(uint8_t bus, uint8_t pin, uint8_t offset)
  163. {
  164. for(uint8_t idx=0; idx < I2C_PINS_COUNT-1; idx++)
  165. if(i2c_valid_pins[idx*4] == bus && i2c_valid_pins[idx*4+offset] == pin) return i2c_valid_pins[idx*4+3];
  166. return 0;
  167. }
  168. // Set Operating Mode - this configures operating mode of the I2C as either Immediate, ISR, or DMA.
  169. // By default Arduino-style begin() calls will initialize to ISR mode. This can
  170. // only be called when the bus is idle (no changing mode in the middle of Tx/Rx).
  171. // Note that Slave mode can only use ISR operation.
  172. // return: 1=success, 0=fail (bus busy)
  173. // parameters:
  174. // opMode = I2C_OP_MODE_ISR, I2C_OP_MODE_DMA, I2C_OP_MODE_IMM
  175. //
  176. uint8_t i2c_t3::setOpMode_(struct i2cStruct* i2c, uint8_t bus, i2c_op_mode opMode)
  177. {
  178. if(*(i2c->S) & I2C_S_BUSY) return 0; // return immediately if bus busy
  179. *(i2c->C1) = I2C_C1_IICEN; // reset I2C modes, stop intr, stop DMA
  180. *(i2c->S) = I2C_S_IICIF | I2C_S_ARBL; // clear status flags just in case
  181. // Slaves can only use ISR
  182. if(i2c->currentMode == I2C_SLAVE) opMode = I2C_OP_MODE_ISR;
  183. if(opMode == I2C_OP_MODE_IMM)
  184. {
  185. i2c->opMode = I2C_OP_MODE_IMM;
  186. }
  187. if(opMode == I2C_OP_MODE_ISR || opMode == I2C_OP_MODE_DMA)
  188. {
  189. // Nested Vec Interrupt Ctrl - enable I2C interrupt
  190. if(bus == 0)
  191. {
  192. NVIC_ENABLE_IRQ(IRQ_I2C0);
  193. I2C0_INTR_FLAG_INIT; // init I2C0 interrupt flag if used
  194. }
  195. #if I2C_BUS_NUM >= 2
  196. if(bus == 1)
  197. {
  198. NVIC_ENABLE_IRQ(IRQ_I2C1);
  199. I2C1_INTR_FLAG_INIT; // init I2C1 interrupt flag if used
  200. }
  201. #endif
  202. #if I2C_BUS_NUM >= 3
  203. if(bus == 2)
  204. {
  205. NVIC_ENABLE_IRQ(IRQ_I2C2);
  206. I2C2_INTR_FLAG_INIT; // init I2C2 interrupt flag if used
  207. }
  208. #endif
  209. #if I2C_BUS_NUM >= 4
  210. if(bus == 3)
  211. {
  212. NVIC_ENABLE_IRQ(IRQ_I2C3);
  213. I2C3_INTR_FLAG_INIT; // init I2C3 interrupt flag if used
  214. }
  215. #endif
  216. if(opMode == I2C_OP_MODE_DMA)
  217. {
  218. // attempt to get a DMA Channel (if not already allocated)
  219. if(i2c->DMA == nullptr)
  220. i2c->DMA = new DMAChannel();
  221. // check if object created but no available channel
  222. if(i2c->DMA != nullptr && i2c->DMA->channel == DMA_NUM_CHANNELS)
  223. {
  224. // revert to ISR mode if no DMA channels avail
  225. delete i2c->DMA;
  226. i2c->DMA = nullptr;
  227. i2c->opMode = I2C_OP_MODE_ISR;
  228. }
  229. else
  230. {
  231. // DMA object has valid channel
  232. if(bus == 0)
  233. {
  234. // setup static DMA settings
  235. i2c->DMA->disableOnCompletion();
  236. i2c->DMA->attachInterrupt(i2c0_isr);
  237. i2c->DMA->interruptAtCompletion();
  238. i2c->DMA->triggerAtHardwareEvent(DMAMUX_SOURCE_I2C0);
  239. }
  240. #if I2C_BUS_NUM >= 2
  241. if(bus == 1)
  242. {
  243. // setup static DMA settings
  244. i2c->DMA->disableOnCompletion();
  245. i2c->DMA->attachInterrupt(i2c1_isr);
  246. i2c->DMA->interruptAtCompletion();
  247. i2c->DMA->triggerAtHardwareEvent(DMAMUX_SOURCE_I2C1);
  248. }
  249. #endif
  250. #if I2C_BUS_NUM >= 3
  251. // note: on T3.6 I2C2 shares DMAMUX with I2C1
  252. if(bus == 2)
  253. {
  254. // setup static DMA settings
  255. i2c->DMA->disableOnCompletion();
  256. i2c->DMA->attachInterrupt(i2c2_isr);
  257. i2c->DMA->interruptAtCompletion();
  258. i2c->DMA->triggerAtHardwareEvent(DMAMUX_SOURCE_I2C2);
  259. }
  260. #endif
  261. #if I2C_BUS_NUM >= 4
  262. // note: on T3.6 I2C3 shares DMAMUX with I2C0
  263. if(bus == 3)
  264. {
  265. // setup static DMA settings
  266. i2c->DMA->disableOnCompletion();
  267. i2c->DMA->attachInterrupt(i2c3_isr);
  268. i2c->DMA->interruptAtCompletion();
  269. i2c->DMA->triggerAtHardwareEvent(DMAMUX_SOURCE_I2C3);
  270. }
  271. #endif
  272. i2c->activeDMA = I2C_DMA_OFF;
  273. i2c->opMode = I2C_OP_MODE_DMA;
  274. }
  275. }
  276. else
  277. i2c->opMode = I2C_OP_MODE_ISR;
  278. }
  279. return 1;
  280. }
  281. // Set I2C rate - reconfigures I2C frequency divider based on supplied bus freq and desired I2C freq.
  282. // This will be done assuming an idealized I2C rate, even though at high I2C rates
  283. // the actual throughput is much lower than theoretical value.
  284. //
  285. // Since the division ratios are quantized with non-uniform spacing, the selected rate
  286. // will be the one using the nearest available divider.
  287. // return: none
  288. // parameters:
  289. // busFreq = bus frequency, typically F_BUS unless reconfigured
  290. // freq = desired I2C frequency (will be quantized to nearest rate), or can be I2C_RATE_XXX enum (deprecated),
  291. // such as I2C_RATE_100, I2C_RATE_400, etc...
  292. //
  293. // Max I2C rate is 1/20th F_BUS. Some examples:
  294. //
  295. // F_CPU F_BUS Max I2C
  296. // (MHz) (MHz) Rate
  297. // ------------- ----- ----------
  298. // 240/120 120 6.0M bus overclock
  299. // 216 108 5.4M bus overclock
  300. // 192/96 96 4.8M bus overclock
  301. // 180 90 4.5M bus overclock
  302. // 240 80 4.0M bus overclock
  303. // 216/144/72 72 3.6M bus overclock
  304. // 192 64 3.2M bus overclock
  305. // 240/180/120 60 3.0M
  306. // 168 56 2.8M
  307. // 216 54 2.7M
  308. // 192/144/96/48 48 2.4M
  309. // 72 36 1.8M
  310. // 24 24 1.2M
  311. // 16 16 800k
  312. // 8 8 400k
  313. // 4 4 200k
  314. // 2 2 100k
  315. //
  316. void i2c_t3::setRate_(struct i2cStruct* i2c, uint32_t busFreq, uint32_t i2cFreq)
  317. {
  318. int32_t target_div = ((busFreq/1000)<<8)/(i2cFreq/1000);
  319. size_t idx;
  320. // find closest divide ratio
  321. for(idx=0; idx < sizeof(i2c_div_num)/sizeof(i2c_div_num[0]) && (i2c_div_num[idx]<<8) <= target_div; idx++);
  322. if(idx && abs(target_div-(i2c_div_num[idx-1]<<8)) <= abs(target_div-(i2c_div_num[idx]<<8))) idx--;
  323. // Set divider to set rate
  324. *(i2c->F) = i2c_div_ratio[idx];
  325. // save current rate setting
  326. i2c->currentRate = busFreq/i2c_div_num[idx];
  327. // Set filter
  328. if(busFreq >= 48000000)
  329. *(i2c->FLT) = 4;
  330. else
  331. *(i2c->FLT) = busFreq/12000000;
  332. }
  333. // ------------------------------------------------------------------------------------------------------
  334. // Configure I2C pins - reconfigures active I2C pins on-the-fly (only works when bus is idle). If reconfig
  335. // set then inactive pins will switch to input mode using same pullup configuration.
  336. // return: 1=success, 0=fail (bus busy or incompatible pins)
  337. // parameters:
  338. // pins = pins to use, can be specified as 'i2c_pins' enum,
  339. // or as 'SCL,SDA' pair (using any valid SCL or SDA), options are:
  340. // Pin Name
  341. // Interface Devices (deprecated) SCL SDA
  342. // --------- ------- -------------- ----- ----- (note: in almost all cases SCL is the
  343. // Wire All I2C_PINS_16_17 16 17 lower pin #, except cases marked *)
  344. // Wire All I2C_PINS_18_19 19 18 *
  345. // Wire 3.5/3.6 I2C_PINS_7_8 7 8
  346. // Wire 3.5/3.6 I2C_PINS_33_34 33 34
  347. // Wire 3.5/3.6 I2C_PINS_47_48 47 48
  348. // Wire1 LC I2C_PINS_22_23 22 23
  349. // Wire1 3.1/3.2 I2C_PINS_26_31 26 31
  350. // Wire1 3.1/3.2 I2C_PINS_29_30 29 30
  351. // Wire1 3.5/3.6 I2C_PINS_37_38 37 38
  352. // Wire2 3.5/3.6 I2C_PINS_3_4 3 4
  353. // Wire3 3.6 I2C_PINS_56_57 57 56 *
  354. // pullup = I2C_PULLUP_EXT, I2C_PULLUP_INT
  355. // reconfig = 1=reconfigure old pins, 0=do not reconfigure old pins (base routine only)
  356. //
  357. #define PIN_CONFIG_ALT(name,alt) uint32_t name = (pullup == I2C_PULLUP_EXT) ? (PORT_PCR_MUX(alt)|PORT_PCR_ODE|PORT_PCR_SRE|PORT_PCR_DSE) \
  358. : (PORT_PCR_MUX(alt)|PORT_PCR_PE|PORT_PCR_PS)
  359. uint8_t i2c_t3::pinConfigure_(struct i2cStruct* i2c, uint8_t bus, uint8_t pinSCL, uint8_t pinSDA, i2c_pullup pullup,
  360. uint8_t configuredSCL, uint8_t configuredSDA)
  361. {
  362. uint8_t validAltSCL, validAltSDA;
  363. volatile uint32_t* pcr;
  364. if((configuredSCL && configuredSDA) && (*(i2c->S) & I2C_S_BUSY)) return 0; // if configured return immediately if bus busy
  365. // Verify new SCL pin is different or not configured, and valid
  366. //
  367. validAltSCL = validPin_(bus, pinSCL, 1);
  368. if((pinSCL != i2c->currentSCL || !configuredSCL) && validAltSCL)
  369. {
  370. // If configured, switch previous pin to non-I2C input
  371. if(configuredSCL) pinMode(i2c->currentSCL, (i2c->currentPullup == I2C_PULLUP_EXT) ? INPUT : INPUT_PULLUP);
  372. // Config new pin
  373. PIN_CONFIG_ALT(configSCL, validAltSCL);
  374. pcr = portConfigRegister(pinSCL);
  375. *pcr = configSCL;
  376. i2c->currentSCL = pinSCL;
  377. i2c->currentPullup = pullup;
  378. i2c->configuredSCL = 1;
  379. }
  380. // Verify new SDA pin is different or not configured, and valid
  381. //
  382. validAltSDA = validPin_(bus, pinSDA, 2);
  383. if((pinSDA != i2c->currentSDA || !configuredSDA) && validAltSDA)
  384. {
  385. // If reconfig set, switch previous pin to non-I2C input
  386. if(configuredSDA) pinMode(i2c->currentSDA, (i2c->currentPullup == I2C_PULLUP_EXT) ? INPUT : INPUT_PULLUP);
  387. // Config new pin
  388. PIN_CONFIG_ALT(configSDA, validAltSDA);
  389. pcr = portConfigRegister(pinSDA);
  390. *pcr = configSDA;
  391. i2c->currentSDA = pinSDA;
  392. i2c->currentPullup = pullup;
  393. i2c->configuredSDA = 1;
  394. }
  395. return (validAltSCL && validAltSDA);
  396. }
  397. // ------------------------------------------------------------------------------------------------------
  398. // Acquire Bus - acquires bus in Master mode and escalates priority as needed, intended
  399. // for internal use only
  400. // return: 1=success, 0=fail (cannot acquire bus)
  401. // parameters:
  402. // timeout = timeout in microseconds
  403. // forceImm = flag to indicate if immediate mode is required
  404. //
  405. uint8_t i2c_t3::acquireBus_(struct i2cStruct* i2c, uint8_t bus, uint32_t timeout, uint8_t& forceImm)
  406. {
  407. elapsedMicros deltaT;
  408. // update timeout
  409. timeout = (timeout == 0) ? i2c->defTimeout : timeout;
  410. // TODO may need to check bus busy before issuing START if multi-master
  411. // start timer, then take control of the bus
  412. deltaT = 0;
  413. if(*(i2c->C1) & I2C_C1_MST)
  414. {
  415. // we are already the bus master, so send a repeated start
  416. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_RSTA | I2C_C1_TX;
  417. }
  418. else
  419. {
  420. while(timeout == 0 || deltaT < timeout)
  421. {
  422. // we are not currently the bus master, so check if bus ready
  423. if(!(*(i2c->S) & I2C_S_BUSY))
  424. {
  425. // become the bus master in transmit mode (send start)
  426. i2c->currentMode = I2C_MASTER;
  427. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
  428. break;
  429. }
  430. }
  431. #if defined(I2C_AUTO_RETRY)
  432. // if not master and auto-retry set, then reset bus and try one last time
  433. if(!(*(i2c->C1) & I2C_C1_MST))
  434. {
  435. resetBus_(i2c,bus);
  436. I2C_ERR_INC(I2C_ERRCNT_RESET_BUS);
  437. if(!(*(i2c->S) & I2C_S_BUSY))
  438. {
  439. // become the bus master in transmit mode (send start)
  440. i2c->currentMode = I2C_MASTER;
  441. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
  442. }
  443. }
  444. #endif
  445. // check if not master
  446. if(!(*(i2c->C1) & I2C_C1_MST))
  447. {
  448. i2c->currentStatus = I2C_NOT_ACQ; // bus not acquired
  449. I2C_ERR_INC(I2C_ERRCNT_NOT_ACQ);
  450. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if cannot acquire bus
  451. return 0;
  452. }
  453. }
  454. #ifndef I2C_DISABLE_PRIORITY_CHECK
  455. // For ISR operation, check if current routine has higher priority than I2C IRQ, and if so
  456. // either escalate priority of I2C IRQ or send I2C using immediate mode.
  457. //
  458. // This check is disabled if the routine is called during an active I2C ISR (assumes it is
  459. // called from ISR callback). This is to prevent runaway escalation with nested Wire calls.
  460. //
  461. int irqPriority, currPriority;
  462. if(!i2c_t3::isrActive && (i2c->opMode == I2C_OP_MODE_ISR || i2c->opMode == I2C_OP_MODE_DMA))
  463. {
  464. currPriority = nvic_execution_priority();
  465. switch(bus)
  466. {
  467. case 0: irqPriority = NVIC_GET_PRIORITY(IRQ_I2C0); break;
  468. #if defined(__MKL26Z64__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) // LC/3.1/3.2/3.5/3.6
  469. case 1: irqPriority = NVIC_GET_PRIORITY(IRQ_I2C1); break;
  470. #endif
  471. #if defined(__MK64FX512__) || defined(__MK66FX1M0__) // 3.5/3.6
  472. case 2: irqPriority = NVIC_GET_PRIORITY(IRQ_I2C2); break;
  473. #endif
  474. #if defined(__MK66FX1M0__) // 3.6
  475. case 3: irqPriority = NVIC_GET_PRIORITY(IRQ_I2C3); break;
  476. #endif
  477. default: irqPriority = NVIC_GET_PRIORITY(IRQ_I2C0); break;
  478. }
  479. if(currPriority <= irqPriority)
  480. {
  481. if(currPriority < 16)
  482. forceImm = 1; // current priority cannot be surpassed, force Immediate mode
  483. else
  484. {
  485. switch(bus)
  486. {
  487. case 0: NVIC_SET_PRIORITY(IRQ_I2C0, currPriority-16); break;
  488. #if defined(__MKL26Z64__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) // LC/3.1/3.2/3.5/3.6
  489. case 1: NVIC_SET_PRIORITY(IRQ_I2C1, currPriority-16); break;
  490. #endif
  491. #if defined(__MK64FX512__) || defined(__MK66FX1M0__) // 3.5/3.6
  492. case 2: NVIC_SET_PRIORITY(IRQ_I2C2, currPriority-16); break;
  493. #endif
  494. #if defined(__MK66FX1M0__) // 3.6
  495. case 3: NVIC_SET_PRIORITY(IRQ_I2C3, currPriority-16); break;
  496. #endif
  497. default: NVIC_SET_PRIORITY(IRQ_I2C0, currPriority-16); break;
  498. }
  499. }
  500. }
  501. }
  502. #endif
  503. return 1;
  504. }
  505. // ------------------------------------------------------------------------------------------------------
  506. // Reset Bus - toggles SCL until SDA line is released (9 clocks max). This is used to correct
  507. // a hung bus in which a Slave device missed some clocks and remains stuck outputting
  508. // a low signal on SDA (thereby preventing START/STOP signaling).
  509. // return: none
  510. //
  511. void i2c_t3::resetBus_(struct i2cStruct* i2c, uint8_t bus)
  512. {
  513. uint8_t scl = i2c->currentSCL;
  514. uint8_t sda = i2c->currentSDA;
  515. // change pin mux to digital I/O
  516. pinMode(sda,((i2c->currentPullup == I2C_PULLUP_EXT) ? INPUT : INPUT_PULLUP));
  517. digitalWrite(scl,HIGH);
  518. pinMode(scl,OUTPUT);
  519. for(uint8_t count=0; digitalRead(sda) == 0 && count < 9; count++)
  520. {
  521. digitalWrite(scl,LOW);
  522. delayMicroseconds(5); // 10us period == 100kHz
  523. digitalWrite(scl,HIGH);
  524. delayMicroseconds(5);
  525. }
  526. // reconfigure pins for I2C
  527. pinConfigure_(i2c, bus, scl, sda, i2c->currentPullup, 0, 0);
  528. // reset config and status
  529. if(*(i2c->S) & 0x7F) // reset config if any residual status bits are set
  530. {
  531. *(i2c->C1) = 0x00; // disable I2C, intr disabled
  532. delayMicroseconds(5);
  533. *(i2c->C1) = I2C_C1_IICEN; // enable I2C, intr disabled, Rx mode
  534. delayMicroseconds(5);
  535. }
  536. i2c->currentStatus = I2C_WAITING;
  537. }
  538. // ------------------------------------------------------------------------------------------------------
  539. // Setup Master Transmit - initialize Tx buffer for transmit to slave at address
  540. // return: none
  541. // parameters:
  542. // address = target 7bit slave address
  543. //
  544. void i2c_t3::beginTransmission(uint8_t address)
  545. {
  546. i2c->txBuffer[0] = (address << 1); // store target addr
  547. i2c->txBufferLength = 1;
  548. clearWriteError(); // clear any previous write error
  549. i2c->currentStatus = I2C_WAITING; // reset status
  550. }
  551. // ------------------------------------------------------------------------------------------------------
  552. // Master Transmit - blocking routine with timeout, transmits Tx buffer to slave. i2c_stop parameter can be used
  553. // to indicate if command should end with a STOP(I2C_STOP) or not (I2C_NOSTOP).
  554. // return: 0=success, 1=data too long, 2=recv addr NACK, 3=recv data NACK, 4=other error
  555. // parameters:
  556. // i2c_stop = I2C_NOSTOP, I2C_STOP
  557. // timeout = timeout in microseconds
  558. //
  559. uint8_t i2c_t3::endTransmission(struct i2cStruct* i2c, uint8_t bus, i2c_stop sendStop, uint32_t timeout)
  560. {
  561. sendTransmission_(i2c, bus, sendStop, timeout);
  562. // wait for completion or timeout
  563. finish_(i2c, bus, timeout);
  564. return getError();
  565. }
  566. // ------------------------------------------------------------------------------------------------------
  567. // Send Master Transmit - non-blocking routine, starts transmit of Tx buffer to slave. i2c_stop parameter can be
  568. // used to indicate if command should end with a STOP (I2C_STOP) or not (I2C_NOSTOP). Use
  569. // done() or finish() to determine completion and status() to determine success/fail.
  570. // return: none
  571. // parameters:
  572. // i2c_stop = I2C_NOSTOP, I2C_STOP
  573. // timeout = timeout in microseconds (only used for Immediate operation)
  574. //
  575. void i2c_t3::sendTransmission_(struct i2cStruct* i2c, uint8_t bus, i2c_stop sendStop, uint32_t timeout)
  576. {
  577. uint8_t status, forceImm=0;
  578. size_t idx;
  579. // exit immediately if sending 0 bytes
  580. if(i2c->txBufferLength == 0) return;
  581. // update timeout
  582. timeout = (timeout == 0) ? i2c->defTimeout : timeout;
  583. // clear the status flags
  584. #if defined(__MKL26Z64__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) // LC/3.5/3.6
  585. *(i2c->FLT) |= I2C_FLT_STOPF | I2C_FLT_STARTF; // clear STOP/START intr
  586. *(i2c->FLT) &= ~I2C_FLT_SSIE; // disable STOP/START intr (not used in Master mode)
  587. #endif
  588. *(i2c->S) = I2C_S_IICIF | I2C_S_ARBL; // clear intr, arbl
  589. // try to take control of the bus
  590. if(!acquireBus_(i2c, bus, timeout, forceImm)) return;
  591. //
  592. // Immediate mode - blocking
  593. //
  594. if(i2c->opMode == I2C_OP_MODE_IMM || forceImm)
  595. {
  596. elapsedMicros deltaT;
  597. i2c->currentStatus = I2C_SENDING;
  598. i2c->currentStop = sendStop;
  599. for(idx=0; idx < i2c->txBufferLength && (timeout == 0 || deltaT < timeout); idx++)
  600. {
  601. // send data, wait for done
  602. *(i2c->D) = i2c->txBuffer[idx];
  603. // wait for byte
  604. while(!(*(i2c->S) & I2C_S_IICIF) && (timeout == 0 || deltaT < timeout));
  605. *(i2c->S) = I2C_S_IICIF;
  606. if(timeout && deltaT >= timeout) break;
  607. status = *(i2c->S);
  608. // check arbitration
  609. if(status & I2C_S_ARBL)
  610. {
  611. i2c->currentStatus = I2C_ARB_LOST;
  612. *(i2c->S) = I2C_S_ARBL; // clear arbl flag
  613. // TODO: this is clearly not right, after ARBL it should drop into IMM slave mode if IAAS=1
  614. // Right now Rx message would be ignored regardless of IAAS
  615. *(i2c->C1) = I2C_C1_IICEN; // change to Rx mode, intr disabled (does this send STOP if ARBL flagged?)
  616. I2C_ERR_INC(I2C_ERRCNT_ARBL);
  617. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if ARBL
  618. return;
  619. }
  620. // check if slave ACK'd
  621. else if(status & I2C_S_RXAK)
  622. {
  623. if(idx == 0)
  624. {
  625. i2c->currentStatus = I2C_ADDR_NAK; // NAK on Addr
  626. I2C_ERR_INC(I2C_ERRCNT_ADDR_NAK);
  627. }
  628. else
  629. {
  630. i2c->currentStatus = I2C_DATA_NAK; // NAK on Data
  631. I2C_ERR_INC(I2C_ERRCNT_DATA_NAK);
  632. }
  633. *(i2c->C1) = I2C_C1_IICEN; // send STOP, change to Rx mode, intr disabled
  634. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if NAK
  635. return;
  636. }
  637. }
  638. // send STOP if configured
  639. if(i2c->currentStop == I2C_STOP)
  640. *(i2c->C1) = I2C_C1_IICEN; // send STOP, change to Rx mode, intr disabled
  641. else
  642. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX; // no STOP, stay in Tx mode, intr disabled
  643. // Set final status
  644. if(idx < i2c->txBufferLength)
  645. {
  646. i2c->currentStatus = I2C_TIMEOUT; // Tx incomplete, mark as timeout
  647. I2C_ERR_INC(I2C_ERRCNT_TIMEOUT);
  648. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if timeout
  649. }
  650. else
  651. {
  652. i2c->currentStatus = I2C_WAITING; // Tx complete, change to waiting state
  653. if(i2c->user_onTransmitDone != nullptr) i2c->user_onTransmitDone(); // Call Master Tx complete callback
  654. }
  655. }
  656. //
  657. // ISR/DMA mode - non-blocking
  658. //
  659. else if(i2c->opMode == I2C_OP_MODE_ISR || i2c->opMode == I2C_OP_MODE_DMA)
  660. {
  661. // send target addr and enable interrupts
  662. i2c->currentStatus = I2C_SENDING;
  663. i2c->currentStop = sendStop;
  664. i2c->txBufferIndex = 0;
  665. if(i2c->opMode == I2C_OP_MODE_DMA && i2c->txBufferLength >= 5) // limit transfers less than 5 bytes to ISR method
  666. {
  667. // init DMA, let the hack begin
  668. i2c->activeDMA = I2C_DMA_ADDR;
  669. i2c->DMA->sourceBuffer(&i2c->txBuffer[2],i2c->txBufferLength-3); // DMA sends all except first/second/last bytes
  670. i2c->DMA->destination(*(i2c->D));
  671. }
  672. // start ISR
  673. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TX; // enable intr
  674. *(i2c->D) = i2c->txBuffer[0]; // writing first data byte will start ISR
  675. }
  676. }
  677. // ------------------------------------------------------------------------------------------------------
  678. // Master Receive - blocking routine with timeout, requests length bytes from slave at address. Receive data will
  679. // be placed in the Rx buffer. i2c_stop parameter can be used to indicate if command should end
  680. // with a STOP (I2C_STOP) or not (I2C_NOSTOP).
  681. // return: #bytes received = success, 0=fail (0 length request, NAK, timeout, or bus error)
  682. // parameters:
  683. // address = target 7bit slave address
  684. // length = number of bytes requested
  685. // i2c_stop = I2C_NOSTOP, I2C_STOP
  686. // timeout = timeout in microseconds
  687. //
  688. size_t i2c_t3::requestFrom_(struct i2cStruct* i2c, uint8_t bus, uint8_t addr, size_t len, i2c_stop sendStop, uint32_t timeout)
  689. {
  690. // exit immediately if request for 0 bytes
  691. if(len == 0) return 0;
  692. sendRequest_(i2c, bus, addr, len, sendStop, timeout);
  693. // wait for completion or timeout
  694. if(finish_(i2c, bus, timeout))
  695. return i2c->rxBufferLength;
  696. else
  697. return 0; // NAK, timeout or bus error
  698. }
  699. // ------------------------------------------------------------------------------------------------------
  700. // Start Master Receive - non-blocking routine, starts request for length bytes from slave at address. Receive
  701. // data will be placed in the Rx buffer. i2c_stop parameter can be used to indicate if
  702. // command should end with a STOP (I2C_STOP) or not (I2C_NOSTOP). Use done() or finish()
  703. // to determine completion and status() to determine success/fail.
  704. // return: none
  705. // parameters:
  706. // address = target 7bit slave address
  707. // length = number of bytes requested
  708. // i2c_stop = I2C_NOSTOP, I2C_STOP
  709. // timeout = timeout in microseconds (only used for Immediate operation)
  710. //
  711. void i2c_t3::sendRequest_(struct i2cStruct* i2c, uint8_t bus, uint8_t addr, size_t len, i2c_stop sendStop, uint32_t timeout)
  712. {
  713. uint8_t status, data, chkTimeout=0, forceImm=0;
  714. // exit immediately if request for 0 bytes or request too large
  715. if(len == 0) return;
  716. if(len > I2C_RX_BUFFER_LENGTH) { i2c->currentStatus=I2C_BUF_OVF; return; }
  717. i2c->reqCount = len; // store request length
  718. i2c->rxBufferIndex = 0; // reset buffer
  719. i2c->rxBufferLength = 0;
  720. timeout = (timeout == 0) ? i2c->defTimeout : timeout;
  721. // clear the status flags
  722. #if defined(__MKL26Z64__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) // LC/3.5/3.6
  723. *(i2c->FLT) |= I2C_FLT_STOPF | I2C_FLT_STARTF; // clear STOP/START intr
  724. *(i2c->FLT) &= ~I2C_FLT_SSIE; // disable STOP/START intr (not used in Master mode)
  725. #endif
  726. *(i2c->S) = I2C_S_IICIF | I2C_S_ARBL; // clear intr, arbl
  727. // try to take control of the bus
  728. if(!acquireBus_(i2c, bus, timeout, forceImm)) return;
  729. //
  730. // Immediate mode - blocking
  731. //
  732. if(i2c->opMode == I2C_OP_MODE_IMM || forceImm)
  733. {
  734. elapsedMicros deltaT;
  735. i2c->currentStatus = I2C_SEND_ADDR;
  736. i2c->currentStop = sendStop;
  737. // Send target address
  738. *(i2c->D) = (addr << 1) | 1; // address + READ
  739. // wait for byte
  740. while(!(*(i2c->S) & I2C_S_IICIF) && (timeout == 0 || deltaT < timeout));
  741. *(i2c->S) = I2C_S_IICIF;
  742. if(timeout && deltaT >= timeout)
  743. {
  744. *(i2c->C1) = I2C_C1_IICEN; // send STOP, change to Rx mode, intr disabled
  745. i2c->currentStatus = I2C_TIMEOUT; // Rx incomplete, mark as timeout
  746. I2C_ERR_INC(I2C_ERRCNT_TIMEOUT);
  747. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if timeout
  748. return;
  749. }
  750. status = *(i2c->S);
  751. // check arbitration
  752. if(status & I2C_S_ARBL)
  753. {
  754. i2c->currentStatus = I2C_ARB_LOST;
  755. *(i2c->S) = I2C_S_ARBL; // clear arbl flag
  756. // TODO: this is clearly not right, after ARBL it should drop into IMM slave mode if IAAS=1
  757. // Right now Rx message would be ignored regardless of IAAS
  758. *(i2c->C1) = I2C_C1_IICEN; // change to Rx mode, intr disabled (does this send STOP if ARBL flagged?)
  759. I2C_ERR_INC(I2C_ERRCNT_ARBL);
  760. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if ARBL
  761. return;
  762. }
  763. // check if slave ACK'd
  764. else if(status & I2C_S_RXAK)
  765. {
  766. i2c->currentStatus = I2C_ADDR_NAK; // NAK on Addr
  767. *(i2c->C1) = I2C_C1_IICEN; // send STOP, change to Rx mode, intr disabled
  768. I2C_ERR_INC(I2C_ERRCNT_ADDR_NAK);
  769. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if NAK
  770. return;
  771. }
  772. else
  773. {
  774. // Slave addr ACK, change to Rx mode
  775. i2c->currentStatus = I2C_RECEIVING;
  776. if(i2c->reqCount == 1)
  777. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TXAK; // no STOP, Rx, NAK on recv
  778. else
  779. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_MST; // no STOP, change to Rx
  780. data = *(i2c->D); // dummy read
  781. // Master receive loop
  782. while(i2c->rxBufferLength < i2c->reqCount && i2c->currentStatus == I2C_RECEIVING)
  783. {
  784. while(!(*(i2c->S) & I2C_S_IICIF) && (timeout == 0 || deltaT < timeout));
  785. *(i2c->S) = I2C_S_IICIF;
  786. chkTimeout = (timeout != 0 && deltaT >= timeout);
  787. // check if 2nd to last byte or timeout
  788. if((i2c->rxBufferLength+2) == i2c->reqCount || (chkTimeout && !i2c->timeoutRxNAK))
  789. {
  790. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TXAK; // no STOP, Rx, NAK on recv
  791. }
  792. // if last byte or timeout send STOP
  793. if((i2c->rxBufferLength+1) >= i2c->reqCount || (chkTimeout && i2c->timeoutRxNAK))
  794. {
  795. i2c->timeoutRxNAK = 0; // clear flag
  796. // change to Tx mode
  797. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
  798. // grab last data
  799. data = *(i2c->D);
  800. i2c->rxBuffer[i2c->rxBufferLength++] = data;
  801. if(i2c->currentStop == I2C_STOP) // NAK then STOP
  802. {
  803. delayMicroseconds(1); // empirical patch, lets things settle before issuing STOP
  804. *(i2c->C1) = I2C_C1_IICEN; // send STOP, change to Rx mode, intr disabled
  805. }
  806. // else NAK no STOP
  807. // Set final status
  808. if(chkTimeout)
  809. {
  810. i2c->currentStatus = I2C_TIMEOUT; // Rx incomplete, mark as timeout
  811. I2C_ERR_INC(I2C_ERRCNT_TIMEOUT);
  812. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if timeout
  813. }
  814. else
  815. {
  816. i2c->currentStatus = I2C_WAITING; // Rx complete, change to waiting state
  817. if(i2c->user_onReqFromDone != nullptr) i2c->user_onReqFromDone(); // Call Master Rx complete callback
  818. }
  819. }
  820. else
  821. {
  822. // grab next data, not last byte, will ACK
  823. i2c->rxBuffer[i2c->rxBufferLength++] = *(i2c->D);
  824. }
  825. if(chkTimeout) i2c->timeoutRxNAK = 1; // set flag to indicate NAK sent
  826. }
  827. }
  828. }
  829. //
  830. // ISR/DMA mode - non-blocking
  831. //
  832. else if(i2c->opMode == I2C_OP_MODE_ISR || i2c->opMode == I2C_OP_MODE_DMA)
  833. {
  834. // send 1st data and enable interrupts
  835. i2c->currentStatus = I2C_SEND_ADDR;
  836. i2c->currentStop = sendStop;
  837. if(i2c->opMode == I2C_OP_MODE_DMA && i2c->reqCount >= 5) // limit transfers less than 5 bytes to ISR method
  838. {
  839. // init DMA, let the hack begin
  840. i2c->activeDMA = I2C_DMA_ADDR;
  841. i2c->DMA->source(*(i2c->D));
  842. i2c->DMA->destinationBuffer(&i2c->rxBuffer[0],i2c->reqCount-1); // DMA gets all except last byte
  843. }
  844. // start ISR
  845. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TX; // enable intr
  846. *(i2c->D) = (addr << 1) | 1; // address + READ
  847. }
  848. }
  849. // ------------------------------------------------------------------------------------------------------
  850. // Get Wire Error - returns "Wire" error code from a failed Tx/Rx command
  851. // return: 0=success, 1=data too long, 2=recv addr NACK, 3=recv data NACK, 4=other error (timeout, arb lost)
  852. //
  853. uint8_t i2c_t3::getError(void)
  854. {
  855. // convert status to Arduino return values (give these a higher priority than buf overflow error)
  856. switch(i2c->currentStatus)
  857. {
  858. case I2C_BUF_OVF: return 1;
  859. case I2C_ADDR_NAK: return 2;
  860. case I2C_DATA_NAK: return 3;
  861. case I2C_ARB_LOST: return 4;
  862. case I2C_TIMEOUT: return 4;
  863. case I2C_NOT_ACQ: return 4;
  864. default: break;
  865. }
  866. if(getWriteError()) return 1; // if write_error was set then flag as buffer overflow
  867. return 0; // no errors
  868. }
  869. // ------------------------------------------------------------------------------------------------------
  870. // Done Check - returns simple complete/not-complete value to indicate I2C status
  871. // return: 1=Tx/Rx complete (with or without errors), 0=still running
  872. //
  873. uint8_t i2c_t3::done_(struct i2cStruct* i2c)
  874. {
  875. return (i2c->currentStatus < I2C_SENDING);
  876. }
  877. // ------------------------------------------------------------------------------------------------------
  878. // Finish - blocking routine with timeout, loops until Tx/Rx is complete or timeout occurs
  879. // return: 1=success (Tx or Rx completed, no error), 0=fail (NAK, timeout or Arb Lost)
  880. // parameters:
  881. // timeout = timeout in microseconds
  882. //
  883. uint8_t i2c_t3::finish_(struct i2cStruct* i2c, uint8_t bus, uint32_t timeout)
  884. {
  885. elapsedMicros deltaT;
  886. // update timeout
  887. timeout = (timeout == 0) ? i2c->defTimeout : timeout;
  888. // wait for completion or timeout
  889. deltaT = 0;
  890. while(!done_(i2c) && (timeout == 0 || deltaT < timeout));
  891. // DMA mode and timeout
  892. if(timeout != 0 && deltaT >= timeout && i2c->opMode == I2C_OP_MODE_DMA && i2c->activeDMA != I2C_DMA_OFF)
  893. {
  894. // If DMA mode times out, then wait for transfer to end then mark it as timeout.
  895. // This is done this way because abruptly ending the DMA seems to cause
  896. // the I2C_S_BUSY flag to get stuck, and I cannot find a reliable way to clear it.
  897. while(!done_(i2c));
  898. i2c->currentStatus = I2C_TIMEOUT;
  899. }
  900. // check exit status, if not done then timeout occurred
  901. if(!done_(i2c)) i2c->currentStatus = I2C_TIMEOUT; // set to timeout state
  902. // delay to allow bus to settle - allow Timeout or STOP to complete and be recognized. Timeouts must
  903. // propagate through ISR, and STOP must be recognized on both
  904. // Master and Slave sides
  905. delayMicroseconds(4);
  906. // note that onTransmitDone, onReqFromDone, onError callbacks are handled in ISR, this is done
  907. // because use of this function is optional on background transfers
  908. if(i2c->currentStatus == I2C_WAITING) return 1;
  909. return 0;
  910. }
  911. // ------------------------------------------------------------------------------------------------------
  912. // Write - write data to Tx buffer
  913. // return: #bytes written = success, 0=fail
  914. // parameters:
  915. // data = data byte
  916. //
  917. size_t i2c_t3::write(uint8_t data)
  918. {
  919. if(i2c->txBufferLength < I2C_TX_BUFFER_LENGTH)
  920. {
  921. i2c->txBuffer[i2c->txBufferLength++] = data;
  922. return 1;
  923. }
  924. setWriteError();
  925. return 0;
  926. }
  927. // ------------------------------------------------------------------------------------------------------
  928. // Write Array - write count number of bytes from data array to Tx buffer
  929. // return: #bytes written = success, 0=fail
  930. // parameters:
  931. // data = pointer to uint8_t array of data
  932. // count = number of bytes to write
  933. //
  934. size_t i2c_t3::write(const uint8_t* data, size_t count)
  935. {
  936. if(i2c->txBufferLength < I2C_TX_BUFFER_LENGTH)
  937. {
  938. size_t avail = I2C_TX_BUFFER_LENGTH - i2c->txBufferLength;
  939. uint8_t* dest = i2c->txBuffer + i2c->txBufferLength;
  940. if(count > avail)
  941. {
  942. count = avail; // truncate to space avail if needed
  943. setWriteError();
  944. }
  945. memcpy(dest, data, count);
  946. i2c->txBufferLength += count;
  947. return count;
  948. }
  949. setWriteError();
  950. return 0;
  951. }
  952. // ------------------------------------------------------------------------------------------------------
  953. // Read - returns next data byte (signed int) from Rx buffer
  954. // return: data, -1 if buffer empty
  955. //
  956. int i2c_t3::read_(struct i2cStruct* i2c)
  957. {
  958. if(i2c->rxBufferIndex >= i2c->rxBufferLength) return -1;
  959. return i2c->rxBuffer[i2c->rxBufferIndex++];
  960. }
  961. // ------------------------------------------------------------------------------------------------------
  962. // Read Array - read count number of bytes from Rx buffer to data array
  963. // return: #bytes read
  964. // parameters:
  965. // data = pointer to uint8_t array of data
  966. // count = number of bytes to write
  967. //
  968. size_t i2c_t3::read_(struct i2cStruct* i2c, uint8_t* data, size_t count)
  969. {
  970. if(i2c->rxBufferLength > i2c->rxBufferIndex)
  971. {
  972. size_t avail = i2c->rxBufferLength - i2c->rxBufferIndex;
  973. uint8_t* src = i2c->rxBuffer + i2c->rxBufferIndex;
  974. if(count > avail) count = avail; // truncate to data avail if needed
  975. memcpy(data, src, count);
  976. i2c->rxBufferIndex += count;
  977. return count;
  978. }
  979. return 0;
  980. }
  981. // ------------------------------------------------------------------------------------------------------
  982. // Peek - returns next data byte (signed int) from Rx buffer without removing it from Rx buffer
  983. // return: data, -1 if buffer empty
  984. //
  985. int i2c_t3::peek_(struct i2cStruct* i2c)
  986. {
  987. if(i2c->rxBufferIndex >= i2c->rxBufferLength) return -1;
  988. return i2c->rxBuffer[i2c->rxBufferIndex];
  989. }
  990. // ------------------------------------------------------------------------------------------------------
  991. // Read Byte - returns next data byte (uint8_t) from Rx buffer
  992. // return: data, 0 if buffer empty
  993. //
  994. uint8_t i2c_t3::readByte_(struct i2cStruct* i2c)
  995. {
  996. if(i2c->rxBufferIndex >= i2c->rxBufferLength) return 0;
  997. return i2c->rxBuffer[i2c->rxBufferIndex++];
  998. }
  999. // ------------------------------------------------------------------------------------------------------
  1000. // Peek Byte - returns next data byte (uint8_t) from Rx buffer without removing it from Rx buffer
  1001. // return: data, 0 if buffer empty
  1002. //
  1003. uint8_t i2c_t3::peekByte_(struct i2cStruct* i2c)
  1004. {
  1005. if(i2c->rxBufferIndex >= i2c->rxBufferLength) return 0;
  1006. return i2c->rxBuffer[i2c->rxBufferIndex];
  1007. }
  1008. // ======================================================================================================
  1009. // ------------------------------------------------------------------------------------------------------
  1010. // I2C Interrupt Service Routine
  1011. // ------------------------------------------------------------------------------------------------------
  1012. // ======================================================================================================
  1013. void i2c0_isr(void) // I2C0 ISR
  1014. {
  1015. I2C0_INTR_FLAG_ON;
  1016. i2c_isr_handler(&(i2c_t3::i2cData[0]),0);
  1017. I2C0_INTR_FLAG_OFF;
  1018. }
  1019. #if I2C_BUS_NUM >= 2
  1020. void i2c1_isr(void) // I2C1 ISR
  1021. {
  1022. I2C1_INTR_FLAG_ON;
  1023. i2c_isr_handler(&(i2c_t3::i2cData[1]),1);
  1024. I2C1_INTR_FLAG_OFF;
  1025. }
  1026. #endif
  1027. #if I2C_BUS_NUM >= 3
  1028. void i2c2_isr(void) // I2C2 ISR
  1029. {
  1030. I2C2_INTR_FLAG_ON;
  1031. i2c_isr_handler(&(i2c_t3::i2cData[2]),2);
  1032. I2C2_INTR_FLAG_OFF;
  1033. }
  1034. #endif
  1035. #if I2C_BUS_NUM >= 4
  1036. void i2c3_isr(void) // I2C3 ISR
  1037. {
  1038. I2C3_INTR_FLAG_ON;
  1039. i2c_isr_handler(&(i2c_t3::i2cData[3]),3);
  1040. I2C3_INTR_FLAG_OFF;
  1041. }
  1042. #endif
  1043. //
  1044. // I2C ISR base handler
  1045. //
  1046. void i2c_isr_handler(struct i2cStruct* i2c, uint8_t bus)
  1047. {
  1048. uint8_t status, c1, data;
  1049. i2c_t3::isrActive++;
  1050. status = *(i2c->S);
  1051. c1 = *(i2c->C1);
  1052. #if defined(__MKL26Z64__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) // LC/3.5/3.6
  1053. uint8_t flt = *(i2c->FLT); // store flags
  1054. #endif
  1055. if(c1 & I2C_C1_MST)
  1056. {
  1057. //
  1058. // Master Mode
  1059. //
  1060. if(c1 & I2C_C1_TX)
  1061. {
  1062. if(i2c->activeDMA == I2C_DMA_BULK || i2c->activeDMA == I2C_DMA_LAST)
  1063. {
  1064. if(i2c->DMA->complete() && i2c->activeDMA == I2C_DMA_BULK)
  1065. {
  1066. // clear DMA interrupt, final byte should trigger another ISR
  1067. i2c->DMA->clearInterrupt();
  1068. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TX; // intr en, Tx mode, DMA disabled
  1069. // DMA says complete at the beginning of its last byte, need to
  1070. // wait until end of its last byte to re-engage ISR
  1071. i2c->activeDMA = I2C_DMA_LAST;
  1072. *(i2c->S) = I2C_S_IICIF; // clear intr
  1073. }
  1074. else if(i2c->activeDMA == I2C_DMA_LAST)
  1075. {
  1076. // wait for TCF
  1077. while(!(*(i2c->S) & I2C_S_TCF));
  1078. // clear DMA, only do this after TCF
  1079. i2c->DMA->clearComplete();
  1080. // re-engage ISR for last byte
  1081. i2c->activeDMA = I2C_DMA_OFF;
  1082. i2c->txBufferIndex = i2c->txBufferLength-1;
  1083. *(i2c->D) = i2c->txBuffer[i2c->txBufferIndex];
  1084. *(i2c->S) = I2C_S_IICIF; // clear intr
  1085. }
  1086. else if(i2c->DMA->error())
  1087. {
  1088. i2c->DMA->clearError();
  1089. i2c->DMA->clearInterrupt();
  1090. i2c->activeDMA = I2C_DMA_OFF;
  1091. i2c->currentStatus = I2C_DMA_ERR;
  1092. I2C_ERR_INC(I2C_ERRCNT_DMA_ERR);
  1093. // check arbitration
  1094. if(status & I2C_S_ARBL)
  1095. {
  1096. // Arbitration Lost
  1097. i2c->currentStatus = I2C_ARB_LOST;
  1098. I2C_ERR_INC(I2C_ERRCNT_ARBL);
  1099. *(i2c->S) = I2C_S_ARBL; // clear arbl flag
  1100. i2c->txBufferIndex = 0; // reset Tx buffer index to prepare for resend
  1101. // TODO does this need to check IAAS and drop to Slave Rx? if so set Rx + dummy read. not sure if this would work for DMA
  1102. }
  1103. *(i2c->C1) = I2C_C1_IICEN; // change to Rx mode, intr disabled, DMA disabled
  1104. *(i2c->S) = I2C_S_IICIF; // clear intr
  1105. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if DMA error or ARBL
  1106. }
  1107. i2c_t3::isrActive--;
  1108. return;
  1109. } // end DMA Tx
  1110. else
  1111. {
  1112. // Continue Master Transmit
  1113. // check if Master Tx or Rx
  1114. if(i2c->currentStatus == I2C_SENDING)
  1115. {
  1116. // check arbitration
  1117. if(status & I2C_S_ARBL)
  1118. {
  1119. // Arbitration Lost
  1120. i2c->activeDMA = I2C_DMA_OFF; // clear pending DMA (if happens on address byte)
  1121. i2c->currentStatus = I2C_ARB_LOST;
  1122. *(i2c->S) = I2C_S_ARBL; // clear arbl flag
  1123. *(i2c->C1) = I2C_C1_IICEN; // change to Rx mode, intr disabled (does this send STOP if ARBL flagged?)
  1124. i2c->txBufferIndex = 0; // reset Tx buffer index to prepare for resend
  1125. // TODO does this need to check IAAS and drop to Slave Rx? if so set Rx + dummy read.
  1126. *(i2c->S) = I2C_S_IICIF; // clear intr
  1127. I2C_ERR_INC(I2C_ERRCNT_ARBL);
  1128. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if ARBL
  1129. }
  1130. // check if slave ACK'd
  1131. else if(status & I2C_S_RXAK)
  1132. {
  1133. i2c->activeDMA = I2C_DMA_OFF; // clear pending DMA (if happens on address byte)
  1134. if(i2c->txBufferIndex == 0)
  1135. {
  1136. i2c->currentStatus = I2C_ADDR_NAK; // NAK on Addr
  1137. I2C_ERR_INC(I2C_ERRCNT_ADDR_NAK);
  1138. }
  1139. else
  1140. {
  1141. i2c->currentStatus = I2C_DATA_NAK; // NAK on Data
  1142. I2C_ERR_INC(I2C_ERRCNT_DATA_NAK);
  1143. }
  1144. // send STOP, change to Rx mode, intr disabled
  1145. // note: Slave NAK is an error, so send STOP regardless of setting
  1146. *(i2c->C1) = I2C_C1_IICEN;
  1147. *(i2c->S) = I2C_S_IICIF; // clear intr
  1148. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if NAK
  1149. }
  1150. else
  1151. {
  1152. // check if last byte transmitted
  1153. if(++i2c->txBufferIndex >= i2c->txBufferLength)
  1154. {
  1155. // Tx complete, change to waiting state
  1156. i2c->currentStatus = I2C_WAITING;
  1157. // send STOP if configured
  1158. if(i2c->currentStop == I2C_STOP)
  1159. *(i2c->C1) = I2C_C1_IICEN; // send STOP, change to Rx mode, intr disabled
  1160. else
  1161. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX; // no STOP, stay in Tx mode, intr disabled
  1162. // run TransmitDone callback when done
  1163. *(i2c->S) = I2C_S_IICIF; // clear intr
  1164. if(i2c->user_onTransmitDone != nullptr) i2c->user_onTransmitDone();
  1165. }
  1166. else if(i2c->activeDMA == I2C_DMA_ADDR)
  1167. {
  1168. // Start DMA
  1169. i2c->activeDMA = I2C_DMA_BULK;
  1170. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TX | I2C_C1_DMAEN; // intr en, Tx mode, DMA en
  1171. i2c->DMA->enable();
  1172. *(i2c->D) = i2c->txBuffer[1]; // DMA will start on next request
  1173. *(i2c->S) = I2C_S_IICIF; // clear intr
  1174. }
  1175. else
  1176. {
  1177. // ISR transmit next byte
  1178. *(i2c->D) = i2c->txBuffer[i2c->txBufferIndex];
  1179. *(i2c->S) = I2C_S_IICIF; // clear intr
  1180. }
  1181. }
  1182. i2c_t3::isrActive--;
  1183. return;
  1184. }
  1185. else if(i2c->currentStatus == I2C_SEND_ADDR)
  1186. {
  1187. // Master Receive, addr sent
  1188. if(status & I2C_S_ARBL)
  1189. {
  1190. // Arbitration Lost
  1191. i2c->currentStatus = I2C_ARB_LOST;
  1192. *(i2c->S) = I2C_S_ARBL; // clear arbl flag
  1193. *(i2c->C1) = I2C_C1_IICEN; // change to Rx mode, intr disabled (does this send STOP if ARBL flagged?)
  1194. // TODO does this need to check IAAS and drop to Slave Rx? if so set Rx + dummy read. not sure if this would work for DMA
  1195. *(i2c->S) = I2C_S_IICIF; // clear intr
  1196. I2C_ERR_INC(I2C_ERRCNT_ARBL);
  1197. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if ARBL
  1198. }
  1199. else if(status & I2C_S_RXAK)
  1200. {
  1201. // Slave addr NAK
  1202. i2c->currentStatus = I2C_ADDR_NAK; // NAK on Addr
  1203. // send STOP, change to Rx mode, intr disabled
  1204. // note: Slave NAK is an error, so send STOP regardless of setting
  1205. *(i2c->C1) = I2C_C1_IICEN;
  1206. *(i2c->S) = I2C_S_IICIF; // clear intr
  1207. I2C_ERR_INC(I2C_ERRCNT_ADDR_NAK);
  1208. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if NAK
  1209. }
  1210. else if(i2c->activeDMA == I2C_DMA_ADDR)
  1211. {
  1212. // Start DMA
  1213. i2c->activeDMA = I2C_DMA_BULK;
  1214. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_DMAEN; // intr en, no STOP, change to Rx, DMA en
  1215. i2c->DMA->enable();
  1216. data = *(i2c->D); // dummy read
  1217. *(i2c->S) = I2C_S_IICIF; // clear intr
  1218. }
  1219. else
  1220. {
  1221. // Slave addr ACK, change to Rx mode
  1222. i2c->currentStatus = I2C_RECEIVING;
  1223. if(i2c->reqCount == 1)
  1224. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TXAK; // no STOP, Rx, NAK on recv
  1225. else
  1226. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST; // no STOP, change to Rx
  1227. data = *(i2c->D); // dummy read
  1228. *(i2c->S) = I2C_S_IICIF; // clear intr
  1229. }
  1230. i2c_t3::isrActive--;
  1231. return;
  1232. }
  1233. else if(i2c->currentStatus == I2C_TIMEOUT)
  1234. {
  1235. // send STOP if configured
  1236. if(i2c->currentStop == I2C_STOP)
  1237. *(i2c->C1) = I2C_C1_IICEN; // send STOP, change to Rx mode, intr disabled
  1238. else
  1239. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX; // no STOP, stay in Tx mode, intr disabled
  1240. *(i2c->S) = I2C_S_IICIF; // clear intr
  1241. I2C_ERR_INC(I2C_ERRCNT_TIMEOUT);
  1242. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if timeout
  1243. i2c_t3::isrActive--;
  1244. return;
  1245. }
  1246. else
  1247. {
  1248. // Should not be in Tx mode if not sending
  1249. // send STOP, change to Rx mode, intr disabled
  1250. *(i2c->C1) = I2C_C1_IICEN;
  1251. *(i2c->S) = I2C_S_IICIF; // clear intr
  1252. i2c_t3::isrActive--;
  1253. return;
  1254. }
  1255. } // end ISR Tx
  1256. }
  1257. else
  1258. {
  1259. // Continue Master Receive
  1260. //
  1261. if(i2c->activeDMA == I2C_DMA_BULK || i2c->activeDMA == I2C_DMA_LAST)
  1262. {
  1263. if(i2c->DMA->complete() && i2c->activeDMA == I2C_DMA_BULK) // 2nd to last byte
  1264. {
  1265. // clear DMA interrupt, final byte should trigger another ISR
  1266. i2c->DMA->clearInterrupt();
  1267. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TXAK; // intr en, Rx mode, DMA disabled, NAK on recv
  1268. i2c->activeDMA = I2C_DMA_LAST;
  1269. *(i2c->S) = I2C_S_IICIF; // clear intr
  1270. }
  1271. else if(i2c->activeDMA == I2C_DMA_LAST) // last byte
  1272. {
  1273. // clear DMA
  1274. i2c->DMA->clearComplete();
  1275. i2c->activeDMA = I2C_DMA_OFF;
  1276. // change to Tx mode
  1277. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
  1278. // grab last data
  1279. i2c->rxBufferLength = i2c->reqCount-1;
  1280. i2c->rxBuffer[i2c->rxBufferLength++] = *(i2c->D);
  1281. if(i2c->currentStop == I2C_STOP) // NAK then STOP
  1282. {
  1283. delayMicroseconds(1); // empirical patch, lets things settle before issuing STOP
  1284. *(i2c->C1) = I2C_C1_IICEN; // send STOP, change to Rx mode, intr disabled
  1285. }
  1286. // else NAK no STOP
  1287. *(i2c->S) = I2C_S_IICIF; // clear intr
  1288. i2c->currentStatus = I2C_WAITING; // Rx complete, change to waiting state
  1289. if(i2c->user_onReqFromDone != nullptr) i2c->user_onReqFromDone(); // Call Master Rx complete callback
  1290. }
  1291. else if(i2c->DMA->error()) // not sure what would cause this...
  1292. {
  1293. i2c->DMA->clearError();
  1294. i2c->DMA->clearInterrupt();
  1295. i2c->activeDMA = I2C_DMA_OFF;
  1296. i2c->currentStatus = I2C_DMA_ERR;
  1297. *(i2c->C1) = I2C_C1_IICEN; // change to Rx mode, intr disabled, DMA disabled
  1298. *(i2c->S) = I2C_S_IICIF; // clear intr
  1299. I2C_ERR_INC(I2C_ERRCNT_DMA_ERR);
  1300. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if DMA error
  1301. }
  1302. i2c_t3::isrActive--;
  1303. return;
  1304. }
  1305. else
  1306. {
  1307. // check if 2nd to last byte or timeout
  1308. if((i2c->rxBufferLength+2) == i2c->reqCount || (i2c->currentStatus == I2C_TIMEOUT && !i2c->timeoutRxNAK))
  1309. {
  1310. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TXAK; // no STOP, Rx, NAK on recv
  1311. }
  1312. // if last byte or timeout send STOP
  1313. if((i2c->rxBufferLength+1) >= i2c->reqCount || (i2c->currentStatus == I2C_TIMEOUT && i2c->timeoutRxNAK))
  1314. {
  1315. i2c->timeoutRxNAK = 0; // clear flag
  1316. // change to Tx mode
  1317. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
  1318. // grab last data
  1319. i2c->rxBuffer[i2c->rxBufferLength++] = *(i2c->D);
  1320. if(i2c->currentStop == I2C_STOP) // NAK then STOP
  1321. {
  1322. delayMicroseconds(1); // empirical patch, lets things settle before issuing STOP
  1323. *(i2c->C1) = I2C_C1_IICEN; // send STOP, change to Rx mode, intr disabled
  1324. }
  1325. // else NAK no STOP
  1326. *(i2c->S) = I2C_S_IICIF; // clear intr
  1327. // Rx complete
  1328. if(i2c->currentStatus == I2C_TIMEOUT)
  1329. {
  1330. I2C_ERR_INC(I2C_ERRCNT_TIMEOUT);
  1331. if(i2c->user_onError != nullptr) i2c->user_onError(); // run Error callback if timeout
  1332. }
  1333. else
  1334. {
  1335. i2c->currentStatus = I2C_WAITING;
  1336. if(i2c->user_onReqFromDone != nullptr) i2c->user_onReqFromDone(); // Call Master Rx complete callback
  1337. }
  1338. }
  1339. else
  1340. {
  1341. // grab next data, not last byte, will ACK
  1342. i2c->rxBuffer[i2c->rxBufferLength++] = *(i2c->D);
  1343. *(i2c->S) = I2C_S_IICIF; // clear intr
  1344. }
  1345. if(i2c->currentStatus == I2C_TIMEOUT && !i2c->timeoutRxNAK)
  1346. i2c->timeoutRxNAK = 1; // set flag to indicate NAK sent
  1347. i2c_t3::isrActive--;
  1348. return;
  1349. }
  1350. }
  1351. }
  1352. else
  1353. {
  1354. //
  1355. // Slave Mode
  1356. //
  1357. // ARBL makes no sense on Slave, but this might get set if there is a pullup problem and
  1358. // SCL/SDA get stuck. This is primarily to guard against ARBL flag getting stuck.
  1359. if(status & I2C_S_ARBL)
  1360. {
  1361. // Arbitration Lost
  1362. *(i2c->S) = I2C_S_ARBL; // clear arbl flag
  1363. if(!(status & I2C_S_IAAS))
  1364. {
  1365. #if defined(__MKL26Z64__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) // LC/3.5/3.6
  1366. *(i2c->FLT) |= I2C_FLT_STOPF | I2C_FLT_STARTF; // clear STOP/START intr
  1367. #endif
  1368. *(i2c->S) = I2C_S_IICIF; // clear intr
  1369. i2c_t3::isrActive--;
  1370. return;
  1371. }
  1372. }
  1373. if(status & I2C_S_IAAS)
  1374. {
  1375. // If in Slave Rx already, then RepSTART occured, run callback
  1376. if(i2c->currentStatus == I2C_SLAVE_RX && i2c->user_onReceive != nullptr)
  1377. {
  1378. i2c->rxBufferIndex = 0;
  1379. i2c->user_onReceive(i2c->rxBufferLength);
  1380. }
  1381. // Is Addressed As Slave
  1382. if(status & I2C_S_SRW)
  1383. {
  1384. // Addressed Slave Transmit
  1385. //
  1386. i2c->currentStatus = I2C_SLAVE_TX;
  1387. i2c->txBufferLength = 0;
  1388. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_TX;
  1389. i2c->rxAddr = (*(i2c->D) >> 1); // read to get target addr
  1390. if(i2c->user_onRequest != nullptr) i2c->user_onRequest(); // load Slave Tx buffer with data
  1391. if(i2c->txBufferLength == 0) i2c->txBuffer[0] = 0; // send 0's if buffer empty
  1392. *(i2c->D) = i2c->txBuffer[0]; // send first data
  1393. i2c->txBufferIndex = 1;
  1394. }
  1395. else
  1396. {
  1397. // Addressed Slave Receive
  1398. //
  1399. // setup SDA-rising ISR - required for STOP detection in Slave Rx mode for 3.0/3.1/3.2
  1400. #if defined(__MK20DX256__) && I2C_BUS_NUM == 2 // 3.1/3.2 (dual-bus)
  1401. i2c->irqCount = 0;
  1402. attachInterrupt(i2c->currentSDA, (bus == 0) ? i2c_t3::sda0_rising_isr : i2c_t3::sda1_rising_isr, RISING);
  1403. #elif defined(__MK20DX128__) || defined(__MK20DX256__) // 3.0/3.1/3.2 (single-bus)
  1404. i2c->irqCount = 0;
  1405. attachInterrupt(i2c->currentSDA, i2c_t3::sda0_rising_isr, RISING);
  1406. #elif defined(__MKL26Z64__) || defined(__MK64FX512__) || defined(__MK66FX1M0__)
  1407. *(i2c->FLT) |= I2C_FLT_SSIE; // enable START/STOP intr for LC/3.5/3.6
  1408. #endif
  1409. i2c->currentStatus = I2C_SLAVE_RX;
  1410. i2c->rxBufferLength = 0;
  1411. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_IICIE;
  1412. i2c->rxAddr = (*(i2c->D) >> 1); // read to get target addr
  1413. }
  1414. #if defined(__MKL26Z64__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) // LC/3.5/3.6
  1415. *(i2c->FLT) |= I2C_FLT_STOPF | I2C_FLT_STARTF; // clear STOP/START intr
  1416. #endif
  1417. *(i2c->S) = I2C_S_IICIF; // clear intr
  1418. i2c_t3::isrActive--;
  1419. return;
  1420. }
  1421. if(c1 & I2C_C1_TX)
  1422. {
  1423. // Continue Slave Transmit
  1424. if((status & I2C_S_RXAK) == 0)
  1425. {
  1426. // Master ACK'd previous byte
  1427. if(i2c->txBufferIndex < i2c->txBufferLength)
  1428. data = i2c->txBuffer[i2c->txBufferIndex++];
  1429. else
  1430. data = 0; // send 0's if buffer empty
  1431. *(i2c->D) = data;
  1432. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_TX;
  1433. }
  1434. else
  1435. {
  1436. // Master did not ACK previous byte
  1437. *(i2c->C1) = I2C_C1_IICEN | I2C_C1_IICIE; // switch to Rx mode
  1438. data = *(i2c->D); // dummy read
  1439. i2c->currentStatus = I2C_WAITING;
  1440. }
  1441. }
  1442. else if(i2c->currentStatus == I2C_SLAVE_RX)
  1443. {
  1444. #if defined(__MKL26Z64__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) // LC/3.5/3.6
  1445. if(flt & (I2C_FLT_STOPF|I2C_FLT_STARTF)) // STOP/START detected, run callback
  1446. {
  1447. // LC (MKL26) appears to have the same I2C_FLT reg definition as 3.6 (K66)
  1448. // There is both STOPF and STARTF and they are both enabled via SSIE, and they must both
  1449. // be cleared in order to work
  1450. *(i2c->FLT) |= I2C_FLT_STOPF | I2C_FLT_STARTF; // clear STOP/START intr
  1451. *(i2c->FLT) &= ~I2C_FLT_SSIE; // disable STOP/START intr (will re-enable on next IAAS)
  1452. *(i2c->S) = I2C_S_IICIF; // clear intr
  1453. i2c->currentStatus = I2C_WAITING;
  1454. // Slave Rx complete, run callback
  1455. if(i2c->user_onReceive != nullptr)
  1456. {
  1457. i2c->rxBufferIndex = 0;
  1458. i2c->user_onReceive(i2c->rxBufferLength);
  1459. }
  1460. i2c_t3::isrActive--;
  1461. return;
  1462. }
  1463. #endif
  1464. // Continue Slave Receive
  1465. //
  1466. // setup SDA-rising ISR - required for STOP detection in Slave Rx mode for 3.0/3.1/3.2
  1467. #if defined(__MK20DX256__) && I2C_BUS_NUM == 2 // 3.1/3.2 (dual-bus)
  1468. i2c->irqCount = 0;
  1469. attachInterrupt(i2c->currentSDA, (bus == 0) ? i2c_t3::sda0_rising_isr : i2c_t3::sda1_rising_isr, RISING);
  1470. #elif defined(__MK20DX128__) || defined(__MK20DX256__) // 3.0/3.1/3.2 (single-bus)
  1471. i2c->irqCount = 0;
  1472. attachInterrupt(i2c->currentSDA, i2c_t3::sda0_rising_isr, RISING);
  1473. #endif
  1474. data = *(i2c->D);
  1475. if(i2c->rxBufferLength < I2C_RX_BUFFER_LENGTH)
  1476. i2c->rxBuffer[i2c->rxBufferLength++] = data;
  1477. }
  1478. #if defined(__MKL26Z64__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) // LC/3.5/3.6
  1479. *(i2c->FLT) |= I2C_FLT_STOPF | I2C_FLT_STARTF; // clear STOP/START intr
  1480. #endif
  1481. *(i2c->S) = I2C_S_IICIF; // clear intr
  1482. }
  1483. }
  1484. #if defined(__MK20DX128__) || defined(__MK20DX256__) // 3.0/3.1/3.2
  1485. // ------------------------------------------------------------------------------------------------------
  1486. // SDA-Rising Interrupt Service Routine - 3.0/3.1/3.2 only
  1487. //
  1488. // Detects the stop condition that terminates a slave receive transfer.
  1489. //
  1490. // I2C0 SDA ISR
  1491. void i2c_t3::sda0_rising_isr(void)
  1492. {
  1493. i2c_t3::sda_rising_isr_handler(&(i2c_t3::i2cData[0]),0);
  1494. }
  1495. #if I2C_BUS_NUM >= 2
  1496. // I2C1 SDA ISR
  1497. void i2c_t3::sda1_rising_isr(void)
  1498. {
  1499. i2c_t3::sda_rising_isr_handler(&(i2c_t3::i2cData[1]),1);
  1500. }
  1501. #endif
  1502. //
  1503. // SDA ISR base handler
  1504. //
  1505. void i2c_t3::sda_rising_isr_handler(struct i2cStruct* i2c, uint8_t bus)
  1506. {
  1507. uint8_t status = *(i2c->S); // capture status first, can change if ISR is too slow
  1508. if(!(status & I2C_S_BUSY))
  1509. {
  1510. i2c->currentStatus = I2C_WAITING;
  1511. detachInterrupt(i2c->currentSDA);
  1512. if(i2c->user_onReceive != nullptr)
  1513. {
  1514. i2c->rxBufferIndex = 0;
  1515. i2c->user_onReceive(i2c->rxBufferLength);
  1516. }
  1517. }
  1518. else
  1519. {
  1520. if(++(i2c->irqCount) >= 2 || !(i2c->currentMode == I2C_SLAVE))
  1521. detachInterrupt(i2c->currentSDA);
  1522. }
  1523. }
  1524. #endif // sda_rising_isr
  1525. // ------------------------------------------------------------------------------------------------------
  1526. // Instantiate
  1527. //
  1528. i2c_t3 Wire = i2c_t3(0); // I2C0
  1529. #if I2C_BUS_NUM >= 2
  1530. i2c_t3 Wire1 = i2c_t3(1); // I2C1
  1531. #endif
  1532. #if I2C_BUS_NUM >= 3
  1533. i2c_t3 Wire2 = i2c_t3(2); // I2C2
  1534. #endif
  1535. #if I2C_BUS_NUM >= 4
  1536. i2c_t3 Wire3 = i2c_t3(3); // I2C3
  1537. #endif
  1538. #endif // i2c_t3
  1539. /*
  1540. ------------------------------------------------------------------------------------------------------
  1541. Changelog
  1542. ------------------------------------------------------------------------------------------------------
  1543. - (v11.0) Modified 01Dec18 by Brian (nox771 at gmail.com)
  1544. - Added state variables and modified pinConfigure_() to recognize unconfigured SCL/SDA pins,
  1545. allowing for setSCL()/setSDA() prior to begin(), which was previously blocked by bus busy
  1546. check on unconfigured pins.
  1547. - Header change to MIT permissive license
  1548. - (v10.1) Modified 02Jan18 by Brian (nox771 at gmail.com)
  1549. - Added User #define to disable priority checks entirely
  1550. - Added i2c_t3::isrActive flag to dynamically disable priority checks during ISR & callbacks.
  1551. This is to prevent runaway priority escalation in cases of callbacks with nested Wire calls.
  1552. - (v10.0) Modified 21Oct17 by Brian (nox771 at gmail.com)
  1553. - Default assignments have been added to many functions for pins/pullup/rate/op_mode, so
  1554. all those parameters are now optional in many function calls (marked ^ below)
  1555. - Unbound SCL/SDA pin assignment. Pins can be specified with either i2c_pins enum or by direct
  1556. SCL,SDA pin definition (using any valid SCL and SDA pin). New function summary is:
  1557. - begin(mode, address1, ^i2c_pins, ^i2c_pullup, ^rate, ^i2c_op_mode)
  1558. - begin(mode, address1, ^pinSCL, ^pinSDA, ^i2c_pullup, ^rate, ^i2c_op_mode)
  1559. - pinConfigure(i2c_pins, ^pullup)
  1560. - pinConfigure(pinSCL, pinSDA, ^pullup)
  1561. - setSCL(pin)
  1562. - setSDA(pin)
  1563. - getSCL()
  1564. - getSDA()
  1565. Note: internal to i2c structure, currentPins has been replaced by currentSCL and currentSDA
  1566. - Added Master callback functions for completion of transfers. Primarily for
  1567. sendTransmission/sendRequest, but these will also work on foreground commands
  1568. endTransmission/requestFrom. Also added an Error callback for Master bus errors.
  1569. - onTransmitDone(function) - where function() is called when Master Transmit is complete
  1570. - onReqFromDone(function) - where function() is called when Master Receive is complete
  1571. - onError(function) - where function() is called upon any I2C error which terminates the
  1572. Master bus operation (eg. NAK, timeout, acquire fail, etc)
  1573. - Fixed blocking conditions that could occur in immediate mode
  1574. - Added error counters which may be optionally enabled via I2C_ERROR_COUNTERS define. When
  1575. enabled it will track (Master mode only): Reset Bus (auto-retry only), Timeout, Addr NAK,
  1576. Data NAK, Arb Lost, Bus Not Acquired, DMA Errors.
  1577. - i2c_err_count enum, getErrorCount(), and zeroErrorCount() functions added
  1578. - (v9.4) Modified 01Oct17 by Brian (nox771 at gmail.com)
  1579. - Fixed Slave ISR for LC/3.5/3.6 not properly recognizing RepSTART
  1580. - Fixed nested Wire calls during Slave ISR receive (calling Wire inside Wire1 Slave ISR)
  1581. - Added uint8_t and char array read functions - Wire.read(databuf, count);
  1582. - (v9.3) Modified 20Sep17 by Brian (nox771 at gmail.com)
  1583. - Fixed Slave ISR for LC/3.5/3.6
  1584. - (v9.2) Modified 29Dec16 by Brian (nox771 at gmail.com)
  1585. - improved resetBus() function to reset C1 state (thanks hw999)
  1586. - (v9.1) Modified 16Oct16 by Brian (nox771 at gmail.com)
  1587. - applied two fixes due to bug reports:
  1588. - removed I2C_F_DIV120 setting (120 divide-ratio) for I2C clock
  1589. - disabled I2C_AUTO_RETRY by default (setting remains but must be manually enabled)
  1590. - (v9) Modified 01Jul16 by Brian (nox771 at gmail.com)
  1591. - Added support for Teensy 3.5/3.6:
  1592. - fully supported (Master/Slave modes, IMM/ISR/DMA operation)
  1593. - supports all available pin/bus options on Wire/Wire1/Wire2/Wire3
  1594. - Fixed LC slave bug, whereby it was incorrectly detecting STOPs directed to other slaves
  1595. - I2C rate is now set using a much more flexible method than previously used (this is partially
  1596. motivated by increasing device count and frequencies). As a result, the fixed set of rate
  1597. enums are no longer needed (however they are currently still supported), and desired I2C
  1598. frequency can be directly specified, eg. for 400kHz, I2C_RATE_400 can be replaced by 400000.
  1599. Some setRate() functions are deprecated due to these changes.
  1600. - (v8) Modified 02Apr15 by Brian (nox771 at gmail.com)
  1601. - added support for Teensy LC:
  1602. - fully supported (Master/Slave modes, IMM/ISR/DMA operation)
  1603. - Wire: pins 16/17 or 18/19, rate limited to I2C_RATE_1200
  1604. - Wire1: pins 22/23, rate limited to I2C_RATE_2400
  1605. - added timeout on acquiring bus (prevents lockup when bus cannot be acquired)
  1606. - added setDefaultTimeout() function for setting the default timeout to apply to all commands
  1607. - added resetBus() function for toggling SCL to release stuck Slave devices
  1608. - added setRate(rate) function, similar to setClock(freq), but using rate specifiers (does not
  1609. require specifying busFreq)
  1610. - added I2C_AUTO_RETRY user define
  1611. - (v7) Modified 09Jan15 by Brian (nox771 at gmail.com)
  1612. - added support for F_BUS frequencies: 60MHz, 56MHz, 48MHz, 36MHz, 24MHz, 16MHz, 8MHz, 4MHz, 2MHz
  1613. - added new rates: I2C_RATE_1800, I2C_RATE_2800, I2C_RATE_3000
  1614. - added new priority escalation - in cases where I2C ISR is blocked by having a lower priority than
  1615. calling function, the I2C will either adjust I2C ISR to a higher
  1616. priority, or switch to Immediate mode as needed.
  1617. - added new operating mode control - I2C can be set to operate in ISR mode, DMA mode (Master only),
  1618. or Immediate Mode (Master only)
  1619. - added new begin() functions to allow setting the initial operating mode:
  1620. - begin(i2c_mode mode, uint8_t address, i2c_pins pins, i2c_pullup pullup, i2c_rate rate,
  1621. i2c_op_mode opMode)
  1622. - begin(i2c_mode mode, uint8_t address1, uint8_t address2, i2c_pins pins, i2c_pullup pullup,
  1623. i2c_rate rate, i2c_op_mode opMode)
  1624. - added new functions:
  1625. - uint8_t setOpMode(i2c_op_mode opMode) - used to change operating mode on the fly
  1626. (only when bus is idle)
  1627. - void sendTransmission() - non-blocking Tx with implicit I2C_STOP, added for symmetry
  1628. with endTransmission()
  1629. - uint8_t setRate(uint32_t busFreq, i2c_rate rate) - used to set I2C clock dividers to get
  1630. desired rate, i2c_rate argument
  1631. - uint8_t setRate(uint32_t busFreq, uint32_t i2cFreq) - used to set I2C clock dividers to get
  1632. desired SCL freq, uint32_t argument
  1633. (quantized to nearest i2c_rate)
  1634. - added new Wire compatibility functions:
  1635. - void setClock(uint32_t i2cFreq) - (note: degenerate form of setRate() with busFreq == F_BUS)
  1636. - uint8_t endTransmission(uint8_t sendStop)
  1637. - uint8_t requestFrom(uint8_t addr, uint8_t len)
  1638. - uint8_t requestFrom(uint8_t addr, uint8_t len, uint8_t sendStop)
  1639. - fixed bug in Slave Range code whereby onRequest() callback occurred prior to updating rxAddr
  1640. instead of after
  1641. - fixed bug in arbitration, was missing from Master Tx mode
  1642. - removed I2C1 defines (now included in kinetis.h)
  1643. - removed all debug code (eliminates rbuf dependency)
  1644. - (v6) Modified 16Jan14 by Brian (nox771 at gmail.com)
  1645. - all new structure using dereferenced pointers instead of hardcoding. This allows functions
  1646. (including ISRs) to be reused across multiple I2C buses. Most functions moved to static,
  1647. which in turn are called by inline user functions. Added new struct (i2cData) for holding all
  1648. bus information.
  1649. - added support for Teensy 3.1 and I2C1 interface on pins 29/30 and 26/31.
  1650. - added header define (I2C_BUS_ENABLE n) to control number of enabled buses (eg. both I2C0 & I2C1
  1651. or just I2C0). When using only I2C0 the code and ram usage will be lower.
  1652. - added interrupt flag (toggles pin high during ISR) with independent defines for I2C0 and
  1653. I2C1 (refer to header file), useful for logic analyzer trigger
  1654. - (v5) Modified 09Jun13 by Brian (nox771 at gmail.com)
  1655. - fixed bug in ISR timeout code in which timeout condition could fail to reset in certain cases
  1656. - fixed bug in Slave mode in sda_rising_isr attach, whereby it was not getting attached on the addr byte
  1657. - moved debug routines so they are entirely defined internal to the library (no end user code req'd)
  1658. - debug routines now use IntervalTimer library
  1659. - added support for range of Slave addresses
  1660. - added getRxAddr() for Slave using addr range to determine its called address
  1661. - removed virtual keyword from all functions (is not a base class)
  1662. - (v1-v4) Modified 26Feb13 by Brian (nox771 at gmail.com)
  1663. - Reworked begin function:
  1664. - added option for pins to use (SCL:SDA on 19:18 or 16:17 - note pin order difference)
  1665. - added option for internal pullup - as mentioned in previous code pullup is very strong,
  1666. approx 190 ohms, but is possibly useful for high speed I2C
  1667. - added option for rates - 100kHz, 200kHz, 300kHz, 400kHz, 600kHz, 800kHz, 1MHz, 1.2MHz, <-- 24/48MHz bus
  1668. 1.5MHz, 2.0MHz, 2.4MHz <-- 48MHz bus only
  1669. - Removed string.h dependency (memcpy)
  1670. - Changed Master modes to interrupt driven
  1671. - Added non-blocking Tx/Rx routines, and status/done/finish routines:
  1672. - sendTransmission() - non-blocking transmit
  1673. - sendRequest() - non-blocking receive
  1674. - status() - reports current status
  1675. - done() - indicates Tx/Rx complete (for main loop polling if I2C is running in background)
  1676. - finish() - loops until Tx/Rx complete or bus error
  1677. - Added readByte()/peekByte() for uint8_t return values (note: returns 0 instead of -1 if buf empty)
  1678. - Added fixes for Slave Rx mode - in short Slave Rx on this part is fubar
  1679. (as proof, notice the difference in the I2Cx_FLT register in the KL25 Sub-Family parts)
  1680. - the SDA-rising ISR hack can work but only detects STOP conditons.
  1681. A slave Rx followed by RepSTART won't be detected since bus remains busy.
  1682. To fix this if IAAS occurs while already in Slave Rx mode then it will
  1683. assume RepSTART occurred and trigger onReceive callback.
  1684. - Separated Tx/Rx buffer sizes for asymmetric devices (adjustable in i2c_t3.h)
  1685. - Changed Tx/Rx buffer indicies to size_t to allow for large (>256 byte) buffers
  1686. - Left debug routines in place (controlled via header defines - default is OFF). If debug is
  1687. enabled, note that it can easily overrun the Debug queue on large I2C transfers, yielding
  1688. garbage output. Adjust ringbuf size (in rbuf.h) and possibly PIT interrupt rate to adjust
  1689. data flow to Serial (note also the buffer in Serial can overflow if written too quickly).
  1690. - Added getError() function to return Wire error code
  1691. - Added pinConfigure() function for changing pins on the fly (only when bus not busy)
  1692. - Added timeouts to endTransmission(), requestFrom(), and finish()
  1693. ------------------------------------------------------------------------------------------------------
  1694. */