pyb_i2c.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include "py/runtime.h"
  29. #include "py/mphal.h"
  30. #include "irq.h"
  31. #include "pin.h"
  32. #include "bufhelper.h"
  33. #include "dma.h"
  34. #include "i2c.h"
  35. #if MICROPY_PY_PYB_LEGACY && MICROPY_HW_ENABLE_HW_I2C
  36. /// \moduleref pyb
  37. /// \class I2C - a two-wire serial protocol
  38. ///
  39. /// I2C is a two-wire protocol for communicating between devices. At the physical
  40. /// level it consists of 2 wires: SCL and SDA, the clock and data lines respectively.
  41. ///
  42. /// I2C objects are created attached to a specific bus. They can be initialised
  43. /// when created, or initialised later on:
  44. ///
  45. /// from pyb import I2C
  46. ///
  47. /// i2c = I2C(1) # create on bus 1
  48. /// i2c = I2C(1, I2C.MASTER) # create and init as a master
  49. /// i2c.init(I2C.MASTER, baudrate=20000) # init as a master
  50. /// i2c.init(I2C.SLAVE, addr=0x42) # init as a slave with given address
  51. /// i2c.deinit() # turn off the peripheral
  52. ///
  53. /// Printing the i2c object gives you information about its configuration.
  54. ///
  55. /// Basic methods for slave are send and recv:
  56. ///
  57. /// i2c.send('abc') # send 3 bytes
  58. /// i2c.send(0x42) # send a single byte, given by the number
  59. /// data = i2c.recv(3) # receive 3 bytes
  60. ///
  61. /// To receive inplace, first create a bytearray:
  62. ///
  63. /// data = bytearray(3) # create a buffer
  64. /// i2c.recv(data) # receive 3 bytes, writing them into data
  65. ///
  66. /// You can specify a timeout (in ms):
  67. ///
  68. /// i2c.send(b'123', timeout=2000) # timout after 2 seconds
  69. ///
  70. /// A master must specify the recipient's address:
  71. ///
  72. /// i2c.init(I2C.MASTER)
  73. /// i2c.send('123', 0x42) # send 3 bytes to slave with address 0x42
  74. /// i2c.send(b'456', addr=0x42) # keyword for address
  75. ///
  76. /// Master also has other methods:
  77. ///
  78. /// i2c.is_ready(0x42) # check if slave 0x42 is ready
  79. /// i2c.scan() # scan for slaves on the bus, returning
  80. /// # a list of valid addresses
  81. /// i2c.mem_read(3, 0x42, 2) # read 3 bytes from memory of slave 0x42,
  82. /// # starting at address 2 in the slave
  83. /// i2c.mem_write('abc', 0x42, 2, timeout=1000)
  84. #define PYB_I2C_MASTER (0)
  85. #define PYB_I2C_SLAVE (1)
  86. #define PYB_I2C_SPEED_STANDARD (100000L)
  87. #define PYB_I2C_SPEED_FULL (400000L)
  88. #define PYB_I2C_SPEED_FAST (1000000L)
  89. #if defined(MICROPY_HW_I2C1_SCL)
  90. I2C_HandleTypeDef I2CHandle1 = {.Instance = NULL};
  91. #endif
  92. #if defined(MICROPY_HW_I2C2_SCL)
  93. I2C_HandleTypeDef I2CHandle2 = {.Instance = NULL};
  94. #endif
  95. #if defined(MICROPY_HW_I2C3_SCL)
  96. I2C_HandleTypeDef I2CHandle3 = {.Instance = NULL};
  97. #endif
  98. #if defined(MICROPY_HW_I2C4_SCL)
  99. I2C_HandleTypeDef I2CHandle4 = {.Instance = NULL};
  100. #endif
  101. STATIC bool pyb_i2c_use_dma[4];
  102. const pyb_i2c_obj_t pyb_i2c_obj[] = {
  103. #if defined(MICROPY_HW_I2C1_SCL)
  104. {{&pyb_i2c_type}, &I2CHandle1, &dma_I2C_1_TX, &dma_I2C_1_RX, &pyb_i2c_use_dma[0]},
  105. #else
  106. {{&pyb_i2c_type}, NULL, NULL, NULL, NULL},
  107. #endif
  108. #if defined(MICROPY_HW_I2C2_SCL)
  109. {{&pyb_i2c_type}, &I2CHandle2, &dma_I2C_2_TX, &dma_I2C_2_RX, &pyb_i2c_use_dma[1]},
  110. #else
  111. {{&pyb_i2c_type}, NULL, NULL, NULL, NULL},
  112. #endif
  113. #if defined(MICROPY_HW_I2C3_SCL)
  114. {{&pyb_i2c_type}, &I2CHandle3, &dma_I2C_3_TX, &dma_I2C_3_RX, &pyb_i2c_use_dma[2]},
  115. #else
  116. {{&pyb_i2c_type}, NULL, NULL, NULL, NULL},
  117. #endif
  118. #if defined(MICROPY_HW_I2C4_SCL)
  119. {{&pyb_i2c_type}, &I2CHandle4, &dma_I2C_4_TX, &dma_I2C_4_RX, &pyb_i2c_use_dma[3]},
  120. #else
  121. {{&pyb_i2c_type}, NULL, NULL, NULL, NULL},
  122. #endif
  123. };
  124. #if defined(STM32F7) || defined(STM32L4) || defined(STM32H7)
  125. // The STM32F0, F3, F7, H7 and L4 use a TIMINGR register rather than ClockSpeed and
  126. // DutyCycle.
  127. #if defined(STM32F746xx)
  128. // The value 0x40912732 was obtained from the DISCOVERY_I2Cx_TIMING constant
  129. // defined in the STM32F7Cube file Drivers/BSP/STM32F746G-Discovery/stm32f7456g_discovery.h
  130. #define MICROPY_HW_I2C_BAUDRATE_TIMING { \
  131. {PYB_I2C_SPEED_STANDARD, 0x40912732}, \
  132. {PYB_I2C_SPEED_FULL, 0x10911823}, \
  133. {PYB_I2C_SPEED_FAST, 0x00611116}, \
  134. }
  135. #define MICROPY_HW_I2C_BAUDRATE_DEFAULT (PYB_I2C_SPEED_FULL)
  136. #define MICROPY_HW_I2C_BAUDRATE_MAX (PYB_I2C_SPEED_FAST)
  137. #elif defined(STM32F722xx) || defined(STM32F723xx) \
  138. || defined(STM32F732xx) || defined(STM32F733xx) \
  139. || defined(STM32F767xx) || defined(STM32F769xx)
  140. // These timing values are for f_I2CCLK=54MHz and are only approximate
  141. #define MICROPY_HW_I2C_BAUDRATE_TIMING { \
  142. {PYB_I2C_SPEED_STANDARD, 0xb0420f13}, \
  143. {PYB_I2C_SPEED_FULL, 0x70330309}, \
  144. {PYB_I2C_SPEED_FAST, 0x50100103}, \
  145. }
  146. #define MICROPY_HW_I2C_BAUDRATE_DEFAULT (PYB_I2C_SPEED_FULL)
  147. #define MICROPY_HW_I2C_BAUDRATE_MAX (PYB_I2C_SPEED_FAST)
  148. #elif defined(STM32H7)
  149. // I2C TIMINGs obtained from the STHAL examples.
  150. #define MICROPY_HW_I2C_BAUDRATE_TIMING { \
  151. {PYB_I2C_SPEED_STANDARD, 0x40604E73}, \
  152. {PYB_I2C_SPEED_FULL, 0x00901954}, \
  153. {PYB_I2C_SPEED_FAST, 0x10810915}, \
  154. }
  155. #define MICROPY_HW_I2C_BAUDRATE_DEFAULT (PYB_I2C_SPEED_FULL)
  156. #define MICROPY_HW_I2C_BAUDRATE_MAX (PYB_I2C_SPEED_FAST)
  157. #elif defined(STM32L4)
  158. // The value 0x90112626 was obtained from the DISCOVERY_I2C1_TIMING constant
  159. // defined in the STM32L4Cube file Drivers/BSP/STM32L476G-Discovery/stm32l476g_discovery.h
  160. #define MICROPY_HW_I2C_BAUDRATE_TIMING {{PYB_I2C_SPEED_STANDARD, 0x90112626}}
  161. #define MICROPY_HW_I2C_BAUDRATE_DEFAULT (PYB_I2C_SPEED_STANDARD)
  162. #define MICROPY_HW_I2C_BAUDRATE_MAX (PYB_I2C_SPEED_STANDARD)
  163. #else
  164. #error "no I2C timings for this MCU"
  165. #endif
  166. STATIC const struct {
  167. uint32_t baudrate;
  168. uint32_t timing;
  169. } pyb_i2c_baudrate_timing[] = MICROPY_HW_I2C_BAUDRATE_TIMING;
  170. #define NUM_BAUDRATE_TIMINGS MP_ARRAY_SIZE(pyb_i2c_baudrate_timing)
  171. STATIC void i2c_set_baudrate(I2C_InitTypeDef *init, uint32_t baudrate) {
  172. for (int i = 0; i < NUM_BAUDRATE_TIMINGS; i++) {
  173. if (pyb_i2c_baudrate_timing[i].baudrate == baudrate) {
  174. init->Timing = pyb_i2c_baudrate_timing[i].timing;
  175. return;
  176. }
  177. }
  178. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  179. "Unsupported I2C baudrate: %u", baudrate));
  180. }
  181. uint32_t pyb_i2c_get_baudrate(I2C_HandleTypeDef *i2c) {
  182. for (int i = 0; i < NUM_BAUDRATE_TIMINGS; i++) {
  183. if (pyb_i2c_baudrate_timing[i].timing == i2c->Init.Timing) {
  184. return pyb_i2c_baudrate_timing[i].baudrate;
  185. }
  186. }
  187. return 0;
  188. }
  189. #else
  190. #define MICROPY_HW_I2C_BAUDRATE_DEFAULT (PYB_I2C_SPEED_FULL)
  191. #define MICROPY_HW_I2C_BAUDRATE_MAX (PYB_I2C_SPEED_FULL)
  192. STATIC void i2c_set_baudrate(I2C_InitTypeDef *init, uint32_t baudrate) {
  193. init->ClockSpeed = baudrate;
  194. init->DutyCycle = I2C_DUTYCYCLE_16_9;
  195. }
  196. uint32_t pyb_i2c_get_baudrate(I2C_HandleTypeDef *i2c) {
  197. uint32_t pfreq = i2c->Instance->CR2 & 0x3f;
  198. uint32_t ccr = i2c->Instance->CCR & 0xfff;
  199. if (i2c->Instance->CCR & 0x8000) {
  200. // Fast mode, assume duty cycle of 16/9
  201. return pfreq * 40000 / ccr;
  202. } else {
  203. // Standard mode
  204. return pfreq * 500000 / ccr;
  205. }
  206. }
  207. #endif
  208. void i2c_init0(void) {
  209. // Initialise the I2C handles.
  210. // The structs live on the BSS so all other fields will be zero after a reset.
  211. #if defined(MICROPY_HW_I2C1_SCL)
  212. I2CHandle1.Instance = I2C1;
  213. #endif
  214. #if defined(MICROPY_HW_I2C2_SCL)
  215. I2CHandle2.Instance = I2C2;
  216. #endif
  217. #if defined(MICROPY_HW_I2C3_SCL)
  218. I2CHandle3.Instance = I2C3;
  219. #endif
  220. #if defined(MICROPY_HW_I2C4_SCL)
  221. I2CHandle4.Instance = I2C4;
  222. #endif
  223. }
  224. void pyb_i2c_init(I2C_HandleTypeDef *i2c) {
  225. int i2c_unit;
  226. const pin_obj_t *scl_pin;
  227. const pin_obj_t *sda_pin;
  228. if (0) {
  229. #if defined(MICROPY_HW_I2C1_SCL)
  230. } else if (i2c == &I2CHandle1) {
  231. i2c_unit = 1;
  232. scl_pin = MICROPY_HW_I2C1_SCL;
  233. sda_pin = MICROPY_HW_I2C1_SDA;
  234. __HAL_RCC_I2C1_CLK_ENABLE();
  235. #endif
  236. #if defined(MICROPY_HW_I2C2_SCL)
  237. } else if (i2c == &I2CHandle2) {
  238. i2c_unit = 2;
  239. scl_pin = MICROPY_HW_I2C2_SCL;
  240. sda_pin = MICROPY_HW_I2C2_SDA;
  241. __HAL_RCC_I2C2_CLK_ENABLE();
  242. #endif
  243. #if defined(MICROPY_HW_I2C3_SCL)
  244. } else if (i2c == &I2CHandle3) {
  245. i2c_unit = 3;
  246. scl_pin = MICROPY_HW_I2C3_SCL;
  247. sda_pin = MICROPY_HW_I2C3_SDA;
  248. __HAL_RCC_I2C3_CLK_ENABLE();
  249. #endif
  250. #if defined(MICROPY_HW_I2C4_SCL)
  251. } else if (i2c == &I2CHandle4) {
  252. i2c_unit = 4;
  253. scl_pin = MICROPY_HW_I2C4_SCL;
  254. sda_pin = MICROPY_HW_I2C4_SDA;
  255. __HAL_RCC_I2C4_CLK_ENABLE();
  256. #endif
  257. } else {
  258. // I2C does not exist for this board (shouldn't get here, should be checked by caller)
  259. return;
  260. }
  261. // init the GPIO lines
  262. uint32_t mode = MP_HAL_PIN_MODE_ALT_OPEN_DRAIN;
  263. uint32_t pull = MP_HAL_PIN_PULL_NONE; // have external pull-up resistors on both lines
  264. mp_hal_pin_config_alt(scl_pin, mode, pull, AF_FN_I2C, i2c_unit);
  265. mp_hal_pin_config_alt(sda_pin, mode, pull, AF_FN_I2C, i2c_unit);
  266. // init the I2C device
  267. if (HAL_I2C_Init(i2c) != HAL_OK) {
  268. // init error
  269. // TODO should raise an exception, but this function is not necessarily going to be
  270. // called via Python, so may not be properly wrapped in an NLR handler
  271. printf("OSError: HAL_I2C_Init failed\n");
  272. return;
  273. }
  274. // invalidate the DMA channels so they are initialised on first use
  275. const pyb_i2c_obj_t *self = &pyb_i2c_obj[i2c_unit - 1];
  276. dma_invalidate_channel(self->tx_dma_descr);
  277. dma_invalidate_channel(self->rx_dma_descr);
  278. if (0) {
  279. #if defined(MICROPY_HW_I2C1_SCL)
  280. } else if (i2c->Instance == I2C1) {
  281. HAL_NVIC_EnableIRQ(I2C1_EV_IRQn);
  282. HAL_NVIC_EnableIRQ(I2C1_ER_IRQn);
  283. #endif
  284. #if defined(MICROPY_HW_I2C2_SCL)
  285. } else if (i2c->Instance == I2C2) {
  286. HAL_NVIC_EnableIRQ(I2C2_EV_IRQn);
  287. HAL_NVIC_EnableIRQ(I2C2_ER_IRQn);
  288. #endif
  289. #if defined(MICROPY_HW_I2C3_SCL)
  290. } else if (i2c->Instance == I2C3) {
  291. HAL_NVIC_EnableIRQ(I2C3_EV_IRQn);
  292. HAL_NVIC_EnableIRQ(I2C3_ER_IRQn);
  293. #endif
  294. #if defined(MICROPY_HW_I2C4_SCL)
  295. } else if (i2c->Instance == I2C4) {
  296. HAL_NVIC_EnableIRQ(I2C4_EV_IRQn);
  297. HAL_NVIC_EnableIRQ(I2C4_ER_IRQn);
  298. #endif
  299. }
  300. }
  301. void i2c_deinit(I2C_HandleTypeDef *i2c) {
  302. HAL_I2C_DeInit(i2c);
  303. if (0) {
  304. #if defined(MICROPY_HW_I2C1_SCL)
  305. } else if (i2c->Instance == I2C1) {
  306. __HAL_RCC_I2C1_FORCE_RESET();
  307. __HAL_RCC_I2C1_RELEASE_RESET();
  308. __HAL_RCC_I2C1_CLK_DISABLE();
  309. HAL_NVIC_DisableIRQ(I2C1_EV_IRQn);
  310. HAL_NVIC_DisableIRQ(I2C1_ER_IRQn);
  311. #endif
  312. #if defined(MICROPY_HW_I2C2_SCL)
  313. } else if (i2c->Instance == I2C2) {
  314. __HAL_RCC_I2C2_FORCE_RESET();
  315. __HAL_RCC_I2C2_RELEASE_RESET();
  316. __HAL_RCC_I2C2_CLK_DISABLE();
  317. HAL_NVIC_DisableIRQ(I2C2_EV_IRQn);
  318. HAL_NVIC_DisableIRQ(I2C2_ER_IRQn);
  319. #endif
  320. #if defined(MICROPY_HW_I2C3_SCL)
  321. } else if (i2c->Instance == I2C3) {
  322. __HAL_RCC_I2C3_FORCE_RESET();
  323. __HAL_RCC_I2C3_RELEASE_RESET();
  324. __HAL_RCC_I2C3_CLK_DISABLE();
  325. HAL_NVIC_DisableIRQ(I2C3_EV_IRQn);
  326. HAL_NVIC_DisableIRQ(I2C3_ER_IRQn);
  327. #endif
  328. #if defined(MICROPY_HW_I2C4_SCL)
  329. } else if (i2c->Instance == I2C4) {
  330. __HAL_RCC_I2C4_FORCE_RESET();
  331. __HAL_RCC_I2C4_RELEASE_RESET();
  332. __HAL_RCC_I2C4_CLK_DISABLE();
  333. HAL_NVIC_DisableIRQ(I2C4_EV_IRQn);
  334. HAL_NVIC_DisableIRQ(I2C4_ER_IRQn);
  335. #endif
  336. }
  337. }
  338. void pyb_i2c_init_freq(const pyb_i2c_obj_t *self, mp_int_t freq) {
  339. I2C_InitTypeDef *init = &self->i2c->Init;
  340. init->AddressingMode = I2C_ADDRESSINGMODE_7BIT;
  341. init->DualAddressMode = I2C_DUALADDRESS_DISABLED;
  342. init->GeneralCallMode = I2C_GENERALCALL_DISABLED;
  343. init->NoStretchMode = I2C_NOSTRETCH_DISABLE;
  344. init->OwnAddress1 = PYB_I2C_MASTER_ADDRESS;
  345. init->OwnAddress2 = 0; // unused
  346. if (freq != -1) {
  347. i2c_set_baudrate(init, MIN(freq, MICROPY_HW_I2C_BAUDRATE_MAX));
  348. }
  349. *self->use_dma = false;
  350. // init the I2C bus
  351. i2c_deinit(self->i2c);
  352. pyb_i2c_init(self->i2c);
  353. }
  354. STATIC void i2c_reset_after_error(I2C_HandleTypeDef *i2c) {
  355. // wait for bus-busy flag to be cleared, with a timeout
  356. for (int timeout = 50; timeout > 0; --timeout) {
  357. if (!__HAL_I2C_GET_FLAG(i2c, I2C_FLAG_BUSY)) {
  358. // stop bit was generated and bus is back to normal
  359. return;
  360. }
  361. mp_hal_delay_ms(1);
  362. }
  363. // bus was/is busy, need to reset the peripheral to get it to work again
  364. i2c_deinit(i2c);
  365. pyb_i2c_init(i2c);
  366. }
  367. void i2c_ev_irq_handler(mp_uint_t i2c_id) {
  368. I2C_HandleTypeDef *hi2c;
  369. switch (i2c_id) {
  370. #if defined(MICROPY_HW_I2C1_SCL)
  371. case 1:
  372. hi2c = &I2CHandle1;
  373. break;
  374. #endif
  375. #if defined(MICROPY_HW_I2C2_SCL)
  376. case 2:
  377. hi2c = &I2CHandle2;
  378. break;
  379. #endif
  380. #if defined(MICROPY_HW_I2C3_SCL)
  381. case 3:
  382. hi2c = &I2CHandle3;
  383. break;
  384. #endif
  385. #if defined(MICROPY_HW_I2C4_SCL)
  386. case 4:
  387. hi2c = &I2CHandle4;
  388. break;
  389. #endif
  390. default:
  391. return;
  392. }
  393. #if defined(STM32F4)
  394. if (hi2c->Instance->SR1 & I2C_FLAG_BTF && hi2c->State == HAL_I2C_STATE_BUSY_TX) {
  395. if (hi2c->XferCount != 0U) {
  396. hi2c->Instance->DR = *hi2c->pBuffPtr++;
  397. hi2c->XferCount--;
  398. } else {
  399. __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
  400. if (hi2c->XferOptions != I2C_FIRST_FRAME) {
  401. hi2c->Instance->CR1 |= I2C_CR1_STOP;
  402. }
  403. hi2c->Mode = HAL_I2C_MODE_NONE;
  404. hi2c->State = HAL_I2C_STATE_READY;
  405. }
  406. }
  407. #else
  408. // if not an F4 MCU, use the HAL's IRQ handler
  409. HAL_I2C_EV_IRQHandler(hi2c);
  410. #endif
  411. }
  412. void i2c_er_irq_handler(mp_uint_t i2c_id) {
  413. I2C_HandleTypeDef *hi2c;
  414. switch (i2c_id) {
  415. #if defined(MICROPY_HW_I2C1_SCL)
  416. case 1:
  417. hi2c = &I2CHandle1;
  418. break;
  419. #endif
  420. #if defined(MICROPY_HW_I2C2_SCL)
  421. case 2:
  422. hi2c = &I2CHandle2;
  423. break;
  424. #endif
  425. #if defined(MICROPY_HW_I2C3_SCL)
  426. case 3:
  427. hi2c = &I2CHandle3;
  428. break;
  429. #endif
  430. #if defined(MICROPY_HW_I2C4_SCL)
  431. case 4:
  432. hi2c = &I2CHandle4;
  433. break;
  434. #endif
  435. default:
  436. return;
  437. }
  438. #if defined(STM32F4)
  439. uint32_t sr1 = hi2c->Instance->SR1;
  440. // I2C Bus error
  441. if (sr1 & I2C_FLAG_BERR) {
  442. hi2c->ErrorCode |= HAL_I2C_ERROR_BERR;
  443. __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR);
  444. }
  445. // I2C Arbitration Loss error
  446. if (sr1 & I2C_FLAG_ARLO) {
  447. hi2c->ErrorCode |= HAL_I2C_ERROR_ARLO;
  448. __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO);
  449. }
  450. // I2C Acknowledge failure
  451. if (sr1 & I2C_FLAG_AF) {
  452. hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
  453. SET_BIT(hi2c->Instance->CR1,I2C_CR1_STOP);
  454. __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
  455. }
  456. // I2C Over-Run/Under-Run
  457. if (sr1 & I2C_FLAG_OVR) {
  458. hi2c->ErrorCode |= HAL_I2C_ERROR_OVR;
  459. __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR);
  460. }
  461. #else
  462. // if not an F4 MCU, use the HAL's IRQ handler
  463. HAL_I2C_ER_IRQHandler(hi2c);
  464. #endif
  465. }
  466. STATIC HAL_StatusTypeDef i2c_wait_dma_finished(I2C_HandleTypeDef *i2c, uint32_t timeout) {
  467. // Note: we can't use WFI to idle in this loop because the DMA completion
  468. // interrupt may occur before the WFI. Hence we miss it and have to wait
  469. // until the next sys-tick (up to 1ms).
  470. uint32_t start = HAL_GetTick();
  471. while (HAL_I2C_GetState(i2c) != HAL_I2C_STATE_READY) {
  472. if (HAL_GetTick() - start >= timeout) {
  473. return HAL_TIMEOUT;
  474. }
  475. }
  476. return HAL_OK;
  477. }
  478. /******************************************************************************/
  479. /* MicroPython bindings */
  480. static inline bool in_master_mode(pyb_i2c_obj_t *self) { return self->i2c->Init.OwnAddress1 == PYB_I2C_MASTER_ADDRESS; }
  481. STATIC void pyb_i2c_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  482. pyb_i2c_obj_t *self = MP_OBJ_TO_PTR(self_in);
  483. uint i2c_num = 0;
  484. if (0) { }
  485. #if defined(MICROPY_HW_I2C1_SCL)
  486. else if (self->i2c->Instance == I2C1) { i2c_num = 1; }
  487. #endif
  488. #if defined(MICROPY_HW_I2C2_SCL)
  489. else if (self->i2c->Instance == I2C2) { i2c_num = 2; }
  490. #endif
  491. #if defined(MICROPY_HW_I2C3_SCL)
  492. else if (self->i2c->Instance == I2C3) { i2c_num = 3; }
  493. #endif
  494. #if defined(MICROPY_HW_I2C4_SCL)
  495. else if (self->i2c->Instance == I2C4) { i2c_num = 4; }
  496. #endif
  497. if (self->i2c->State == HAL_I2C_STATE_RESET) {
  498. mp_printf(print, "I2C(%u)", i2c_num);
  499. } else {
  500. if (in_master_mode(self)) {
  501. mp_printf(print, "I2C(%u, I2C.MASTER, baudrate=%u)", i2c_num, pyb_i2c_get_baudrate(self->i2c));
  502. } else {
  503. mp_printf(print, "I2C(%u, I2C.SLAVE, addr=0x%02x)", i2c_num, (self->i2c->Instance->OAR1 >> 1) & 0x7f);
  504. }
  505. }
  506. }
  507. /// \method init(mode, *, addr=0x12, baudrate=400000, gencall=False)
  508. ///
  509. /// Initialise the I2C bus with the given parameters:
  510. ///
  511. /// - `mode` must be either `I2C.MASTER` or `I2C.SLAVE`
  512. /// - `addr` is the 7-bit address (only sensible for a slave)
  513. /// - `baudrate` is the SCL clock rate (only sensible for a master)
  514. /// - `gencall` is whether to support general call mode
  515. STATIC mp_obj_t pyb_i2c_init_helper(const pyb_i2c_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  516. static const mp_arg_t allowed_args[] = {
  517. { MP_QSTR_mode, MP_ARG_INT, {.u_int = PYB_I2C_MASTER} },
  518. { MP_QSTR_addr, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0x12} },
  519. { MP_QSTR_baudrate, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = MICROPY_HW_I2C_BAUDRATE_DEFAULT} },
  520. { MP_QSTR_gencall, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
  521. { MP_QSTR_dma, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
  522. };
  523. // parse args
  524. mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
  525. mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
  526. // set the I2C configuration values
  527. I2C_InitTypeDef *init = &self->i2c->Init;
  528. if (args[0].u_int == PYB_I2C_MASTER) {
  529. // use a special address to indicate we are a master
  530. init->OwnAddress1 = PYB_I2C_MASTER_ADDRESS;
  531. } else {
  532. init->OwnAddress1 = (args[1].u_int << 1) & 0xfe;
  533. }
  534. i2c_set_baudrate(init, MIN(args[2].u_int, MICROPY_HW_I2C_BAUDRATE_MAX));
  535. init->AddressingMode = I2C_ADDRESSINGMODE_7BIT;
  536. init->DualAddressMode = I2C_DUALADDRESS_DISABLED;
  537. init->GeneralCallMode = args[3].u_bool ? I2C_GENERALCALL_ENABLED : I2C_GENERALCALL_DISABLED;
  538. init->OwnAddress2 = 0; // unused
  539. init->NoStretchMode = I2C_NOSTRETCH_DISABLE;
  540. *self->use_dma = args[4].u_bool;
  541. // init the I2C bus
  542. i2c_deinit(self->i2c);
  543. pyb_i2c_init(self->i2c);
  544. return mp_const_none;
  545. }
  546. /// \classmethod \constructor(bus, ...)
  547. ///
  548. /// Construct an I2C object on the given bus. `bus` can be 1 or 2.
  549. /// With no additional parameters, the I2C object is created but not
  550. /// initialised (it has the settings from the last initialisation of
  551. /// the bus, if any). If extra arguments are given, the bus is initialised.
  552. /// See `init` for parameters of initialisation.
  553. ///
  554. /// The physical pins of the I2C busses are:
  555. ///
  556. /// - `I2C(1)` is on the X position: `(SCL, SDA) = (X9, X10) = (PB6, PB7)`
  557. /// - `I2C(2)` is on the Y position: `(SCL, SDA) = (Y9, Y10) = (PB10, PB11)`
  558. STATIC mp_obj_t pyb_i2c_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  559. // check arguments
  560. mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
  561. // work out i2c bus
  562. int i2c_id = 0;
  563. if (MP_OBJ_IS_STR(args[0])) {
  564. const char *port = mp_obj_str_get_str(args[0]);
  565. if (0) {
  566. #ifdef MICROPY_HW_I2C1_NAME
  567. } else if (strcmp(port, MICROPY_HW_I2C1_NAME) == 0) {
  568. i2c_id = 1;
  569. #endif
  570. #ifdef MICROPY_HW_I2C2_NAME
  571. } else if (strcmp(port, MICROPY_HW_I2C2_NAME) == 0) {
  572. i2c_id = 2;
  573. #endif
  574. #ifdef MICROPY_HW_I2C3_NAME
  575. } else if (strcmp(port, MICROPY_HW_I2C3_NAME) == 0) {
  576. i2c_id = 3;
  577. #endif
  578. #ifdef MICROPY_HW_I2C4_NAME
  579. } else if (strcmp(port, MICROPY_HW_I2C4_NAME) == 0) {
  580. i2c_id = 4;
  581. #endif
  582. } else {
  583. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  584. "I2C(%s) doesn't exist", port));
  585. }
  586. } else {
  587. i2c_id = mp_obj_get_int(args[0]);
  588. if (i2c_id < 1 || i2c_id > MP_ARRAY_SIZE(pyb_i2c_obj)
  589. || pyb_i2c_obj[i2c_id - 1].i2c == NULL) {
  590. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  591. "I2C(%d) doesn't exist", i2c_id));
  592. }
  593. }
  594. // get I2C object
  595. const pyb_i2c_obj_t *i2c_obj = &pyb_i2c_obj[i2c_id - 1];
  596. if (n_args > 1 || n_kw > 0) {
  597. // start the peripheral
  598. mp_map_t kw_args;
  599. mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
  600. pyb_i2c_init_helper(i2c_obj, n_args - 1, args + 1, &kw_args);
  601. }
  602. return MP_OBJ_FROM_PTR(i2c_obj);
  603. }
  604. STATIC mp_obj_t pyb_i2c_init_(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
  605. return pyb_i2c_init_helper(MP_OBJ_TO_PTR(args[0]), n_args - 1, args + 1, kw_args);
  606. }
  607. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_init_obj, 1, pyb_i2c_init_);
  608. /// \method deinit()
  609. /// Turn off the I2C bus.
  610. STATIC mp_obj_t pyb_i2c_deinit(mp_obj_t self_in) {
  611. pyb_i2c_obj_t *self = MP_OBJ_TO_PTR(self_in);
  612. i2c_deinit(self->i2c);
  613. return mp_const_none;
  614. }
  615. STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_i2c_deinit_obj, pyb_i2c_deinit);
  616. /// \method is_ready(addr)
  617. /// Check if an I2C device responds to the given address. Only valid when in master mode.
  618. STATIC mp_obj_t pyb_i2c_is_ready(mp_obj_t self_in, mp_obj_t i2c_addr_o) {
  619. pyb_i2c_obj_t *self = MP_OBJ_TO_PTR(self_in);
  620. if (!in_master_mode(self)) {
  621. mp_raise_TypeError("I2C must be a master");
  622. }
  623. mp_uint_t i2c_addr = mp_obj_get_int(i2c_addr_o) << 1;
  624. for (int i = 0; i < 10; i++) {
  625. HAL_StatusTypeDef status = HAL_I2C_IsDeviceReady(self->i2c, i2c_addr, 10, 200);
  626. if (status == HAL_OK) {
  627. return mp_const_true;
  628. }
  629. }
  630. return mp_const_false;
  631. }
  632. STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_i2c_is_ready_obj, pyb_i2c_is_ready);
  633. /// \method scan()
  634. /// Scan all I2C addresses from 0x08 to 0x77 and return a list of those that respond.
  635. /// Only valid when in master mode.
  636. STATIC mp_obj_t pyb_i2c_scan(mp_obj_t self_in) {
  637. pyb_i2c_obj_t *self = MP_OBJ_TO_PTR(self_in);
  638. if (!in_master_mode(self)) {
  639. mp_raise_TypeError("I2C must be a master");
  640. }
  641. mp_obj_t list = mp_obj_new_list(0, NULL);
  642. for (uint addr = 0x08; addr <= 0x77; addr++) {
  643. HAL_StatusTypeDef status = HAL_I2C_IsDeviceReady(self->i2c, addr << 1, 1, 200);
  644. if (status == HAL_OK) {
  645. mp_obj_list_append(list, MP_OBJ_NEW_SMALL_INT(addr));
  646. }
  647. }
  648. return list;
  649. }
  650. STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_i2c_scan_obj, pyb_i2c_scan);
  651. /// \method send(send, addr=0x00, timeout=5000)
  652. /// Send data on the bus:
  653. ///
  654. /// - `send` is the data to send (an integer to send, or a buffer object)
  655. /// - `addr` is the address to send to (only required in master mode)
  656. /// - `timeout` is the timeout in milliseconds to wait for the send
  657. ///
  658. /// Return value: `None`.
  659. STATIC mp_obj_t pyb_i2c_send(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  660. static const mp_arg_t allowed_args[] = {
  661. { MP_QSTR_send, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
  662. { MP_QSTR_addr, MP_ARG_INT, {.u_int = PYB_I2C_MASTER_ADDRESS} },
  663. { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
  664. };
  665. // parse args
  666. pyb_i2c_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]);
  667. mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
  668. mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
  669. // get the buffer to send from
  670. mp_buffer_info_t bufinfo;
  671. uint8_t data[1];
  672. pyb_buf_get_for_send(args[0].u_obj, &bufinfo, data);
  673. // if option is set and IRQs are enabled then we can use DMA
  674. bool use_dma = *self->use_dma && query_irq() == IRQ_STATE_ENABLED;
  675. DMA_HandleTypeDef tx_dma;
  676. if (use_dma) {
  677. dma_init(&tx_dma, self->tx_dma_descr, self->i2c);
  678. self->i2c->hdmatx = &tx_dma;
  679. self->i2c->hdmarx = NULL;
  680. }
  681. // send the data
  682. HAL_StatusTypeDef status;
  683. if (in_master_mode(self)) {
  684. if (args[1].u_int == PYB_I2C_MASTER_ADDRESS) {
  685. if (use_dma) {
  686. dma_deinit(self->tx_dma_descr);
  687. }
  688. mp_raise_TypeError("addr argument required");
  689. }
  690. mp_uint_t i2c_addr = args[1].u_int << 1;
  691. if (!use_dma) {
  692. status = HAL_I2C_Master_Transmit(self->i2c, i2c_addr, bufinfo.buf, bufinfo.len, args[2].u_int);
  693. } else {
  694. MP_HAL_CLEAN_DCACHE(bufinfo.buf, bufinfo.len);
  695. status = HAL_I2C_Master_Transmit_DMA(self->i2c, i2c_addr, bufinfo.buf, bufinfo.len);
  696. }
  697. } else {
  698. if (!use_dma) {
  699. status = HAL_I2C_Slave_Transmit(self->i2c, bufinfo.buf, bufinfo.len, args[2].u_int);
  700. } else {
  701. MP_HAL_CLEAN_DCACHE(bufinfo.buf, bufinfo.len);
  702. status = HAL_I2C_Slave_Transmit_DMA(self->i2c, bufinfo.buf, bufinfo.len);
  703. }
  704. }
  705. // if we used DMA, wait for it to finish
  706. if (use_dma) {
  707. if (status == HAL_OK) {
  708. status = i2c_wait_dma_finished(self->i2c, args[2].u_int);
  709. }
  710. dma_deinit(self->tx_dma_descr);
  711. }
  712. if (status != HAL_OK) {
  713. i2c_reset_after_error(self->i2c);
  714. mp_hal_raise(status);
  715. }
  716. return mp_const_none;
  717. }
  718. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_send_obj, 1, pyb_i2c_send);
  719. /// \method recv(recv, addr=0x00, timeout=5000)
  720. ///
  721. /// Receive data on the bus:
  722. ///
  723. /// - `recv` can be an integer, which is the number of bytes to receive,
  724. /// or a mutable buffer, which will be filled with received bytes
  725. /// - `addr` is the address to receive from (only required in master mode)
  726. /// - `timeout` is the timeout in milliseconds to wait for the receive
  727. ///
  728. /// Return value: if `recv` is an integer then a new buffer of the bytes received,
  729. /// otherwise the same buffer that was passed in to `recv`.
  730. STATIC mp_obj_t pyb_i2c_recv(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  731. static const mp_arg_t allowed_args[] = {
  732. { MP_QSTR_recv, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
  733. { MP_QSTR_addr, MP_ARG_INT, {.u_int = PYB_I2C_MASTER_ADDRESS} },
  734. { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
  735. };
  736. // parse args
  737. pyb_i2c_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]);
  738. mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
  739. mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
  740. // get the buffer to receive into
  741. vstr_t vstr;
  742. mp_obj_t o_ret = pyb_buf_get_for_recv(args[0].u_obj, &vstr);
  743. // if option is set and IRQs are enabled then we can use DMA
  744. bool use_dma = *self->use_dma && query_irq() == IRQ_STATE_ENABLED;
  745. DMA_HandleTypeDef rx_dma;
  746. if (use_dma) {
  747. dma_init(&rx_dma, self->rx_dma_descr, self->i2c);
  748. self->i2c->hdmatx = NULL;
  749. self->i2c->hdmarx = &rx_dma;
  750. }
  751. // receive the data
  752. HAL_StatusTypeDef status;
  753. if (in_master_mode(self)) {
  754. if (args[1].u_int == PYB_I2C_MASTER_ADDRESS) {
  755. mp_raise_TypeError("addr argument required");
  756. }
  757. mp_uint_t i2c_addr = args[1].u_int << 1;
  758. if (!use_dma) {
  759. status = HAL_I2C_Master_Receive(self->i2c, i2c_addr, (uint8_t*)vstr.buf, vstr.len, args[2].u_int);
  760. } else {
  761. MP_HAL_CLEANINVALIDATE_DCACHE(vstr.buf, vstr.len);
  762. status = HAL_I2C_Master_Receive_DMA(self->i2c, i2c_addr, (uint8_t*)vstr.buf, vstr.len);
  763. }
  764. } else {
  765. if (!use_dma) {
  766. status = HAL_I2C_Slave_Receive(self->i2c, (uint8_t*)vstr.buf, vstr.len, args[2].u_int);
  767. } else {
  768. MP_HAL_CLEANINVALIDATE_DCACHE(vstr.buf, vstr.len);
  769. status = HAL_I2C_Slave_Receive_DMA(self->i2c, (uint8_t*)vstr.buf, vstr.len);
  770. }
  771. }
  772. // if we used DMA, wait for it to finish
  773. if (use_dma) {
  774. if (status == HAL_OK) {
  775. status = i2c_wait_dma_finished(self->i2c, args[2].u_int);
  776. }
  777. dma_deinit(self->rx_dma_descr);
  778. }
  779. if (status != HAL_OK) {
  780. i2c_reset_after_error(self->i2c);
  781. mp_hal_raise(status);
  782. }
  783. // return the received data
  784. if (o_ret != MP_OBJ_NULL) {
  785. return o_ret;
  786. } else {
  787. return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
  788. }
  789. }
  790. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_recv_obj, 1, pyb_i2c_recv);
  791. /// \method mem_read(data, addr, memaddr, timeout=5000, addr_size=8)
  792. ///
  793. /// Read from the memory of an I2C device:
  794. ///
  795. /// - `data` can be an integer or a buffer to read into
  796. /// - `addr` is the I2C device address
  797. /// - `memaddr` is the memory location within the I2C device
  798. /// - `timeout` is the timeout in milliseconds to wait for the read
  799. /// - `addr_size` selects width of memaddr: 8 or 16 bits
  800. ///
  801. /// Returns the read data.
  802. /// This is only valid in master mode.
  803. STATIC const mp_arg_t pyb_i2c_mem_read_allowed_args[] = {
  804. { MP_QSTR_data, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
  805. { MP_QSTR_addr, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} },
  806. { MP_QSTR_memaddr, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} },
  807. { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
  808. { MP_QSTR_addr_size, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} },
  809. };
  810. STATIC mp_obj_t pyb_i2c_mem_read(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  811. // parse args
  812. pyb_i2c_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]);
  813. mp_arg_val_t args[MP_ARRAY_SIZE(pyb_i2c_mem_read_allowed_args)];
  814. mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(pyb_i2c_mem_read_allowed_args), pyb_i2c_mem_read_allowed_args, args);
  815. if (!in_master_mode(self)) {
  816. mp_raise_TypeError("I2C must be a master");
  817. }
  818. // get the buffer to read into
  819. vstr_t vstr;
  820. mp_obj_t o_ret = pyb_buf_get_for_recv(args[0].u_obj, &vstr);
  821. // get the addresses
  822. mp_uint_t i2c_addr = args[1].u_int << 1;
  823. mp_uint_t mem_addr = args[2].u_int;
  824. // determine width of mem_addr; default is 8 bits, entering any other value gives 16 bit width
  825. mp_uint_t mem_addr_size = I2C_MEMADD_SIZE_8BIT;
  826. if (args[4].u_int != 8) {
  827. mem_addr_size = I2C_MEMADD_SIZE_16BIT;
  828. }
  829. // if option is set and IRQs are enabled then we can use DMA
  830. bool use_dma = *self->use_dma && query_irq() == IRQ_STATE_ENABLED;
  831. HAL_StatusTypeDef status;
  832. if (!use_dma) {
  833. status = HAL_I2C_Mem_Read(self->i2c, i2c_addr, mem_addr, mem_addr_size, (uint8_t*)vstr.buf, vstr.len, args[3].u_int);
  834. } else {
  835. DMA_HandleTypeDef rx_dma;
  836. dma_init(&rx_dma, self->rx_dma_descr, self->i2c);
  837. self->i2c->hdmatx = NULL;
  838. self->i2c->hdmarx = &rx_dma;
  839. MP_HAL_CLEANINVALIDATE_DCACHE(vstr.buf, vstr.len);
  840. status = HAL_I2C_Mem_Read_DMA(self->i2c, i2c_addr, mem_addr, mem_addr_size, (uint8_t*)vstr.buf, vstr.len);
  841. if (status == HAL_OK) {
  842. status = i2c_wait_dma_finished(self->i2c, args[3].u_int);
  843. }
  844. dma_deinit(self->rx_dma_descr);
  845. }
  846. if (status != HAL_OK) {
  847. i2c_reset_after_error(self->i2c);
  848. mp_hal_raise(status);
  849. }
  850. // return the read data
  851. if (o_ret != MP_OBJ_NULL) {
  852. return o_ret;
  853. } else {
  854. return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
  855. }
  856. }
  857. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_mem_read_obj, 1, pyb_i2c_mem_read);
  858. /// \method mem_write(data, addr, memaddr, timeout=5000, addr_size=8)
  859. ///
  860. /// Write to the memory of an I2C device:
  861. ///
  862. /// - `data` can be an integer or a buffer to write from
  863. /// - `addr` is the I2C device address
  864. /// - `memaddr` is the memory location within the I2C device
  865. /// - `timeout` is the timeout in milliseconds to wait for the write
  866. /// - `addr_size` selects width of memaddr: 8 or 16 bits
  867. ///
  868. /// Returns `None`.
  869. /// This is only valid in master mode.
  870. STATIC mp_obj_t pyb_i2c_mem_write(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  871. // parse args (same as mem_read)
  872. pyb_i2c_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]);
  873. mp_arg_val_t args[MP_ARRAY_SIZE(pyb_i2c_mem_read_allowed_args)];
  874. mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(pyb_i2c_mem_read_allowed_args), pyb_i2c_mem_read_allowed_args, args);
  875. if (!in_master_mode(self)) {
  876. mp_raise_TypeError("I2C must be a master");
  877. }
  878. // get the buffer to write from
  879. mp_buffer_info_t bufinfo;
  880. uint8_t data[1];
  881. pyb_buf_get_for_send(args[0].u_obj, &bufinfo, data);
  882. // get the addresses
  883. mp_uint_t i2c_addr = args[1].u_int << 1;
  884. mp_uint_t mem_addr = args[2].u_int;
  885. // determine width of mem_addr; default is 8 bits, entering any other value gives 16 bit width
  886. mp_uint_t mem_addr_size = I2C_MEMADD_SIZE_8BIT;
  887. if (args[4].u_int != 8) {
  888. mem_addr_size = I2C_MEMADD_SIZE_16BIT;
  889. }
  890. // if option is set and IRQs are enabled then we can use DMA
  891. bool use_dma = *self->use_dma && query_irq() == IRQ_STATE_ENABLED;
  892. HAL_StatusTypeDef status;
  893. if (!use_dma) {
  894. status = HAL_I2C_Mem_Write(self->i2c, i2c_addr, mem_addr, mem_addr_size, bufinfo.buf, bufinfo.len, args[3].u_int);
  895. } else {
  896. DMA_HandleTypeDef tx_dma;
  897. dma_init(&tx_dma, self->tx_dma_descr, self->i2c);
  898. self->i2c->hdmatx = &tx_dma;
  899. self->i2c->hdmarx = NULL;
  900. MP_HAL_CLEAN_DCACHE(bufinfo.buf, bufinfo.len);
  901. status = HAL_I2C_Mem_Write_DMA(self->i2c, i2c_addr, mem_addr, mem_addr_size, bufinfo.buf, bufinfo.len);
  902. if (status == HAL_OK) {
  903. status = i2c_wait_dma_finished(self->i2c, args[3].u_int);
  904. }
  905. dma_deinit(self->tx_dma_descr);
  906. }
  907. if (status != HAL_OK) {
  908. i2c_reset_after_error(self->i2c);
  909. mp_hal_raise(status);
  910. }
  911. return mp_const_none;
  912. }
  913. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_mem_write_obj, 1, pyb_i2c_mem_write);
  914. STATIC const mp_rom_map_elem_t pyb_i2c_locals_dict_table[] = {
  915. // instance methods
  916. { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_i2c_init_obj) },
  917. { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_i2c_deinit_obj) },
  918. { MP_ROM_QSTR(MP_QSTR_is_ready), MP_ROM_PTR(&pyb_i2c_is_ready_obj) },
  919. { MP_ROM_QSTR(MP_QSTR_scan), MP_ROM_PTR(&pyb_i2c_scan_obj) },
  920. { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&pyb_i2c_send_obj) },
  921. { MP_ROM_QSTR(MP_QSTR_recv), MP_ROM_PTR(&pyb_i2c_recv_obj) },
  922. { MP_ROM_QSTR(MP_QSTR_mem_read), MP_ROM_PTR(&pyb_i2c_mem_read_obj) },
  923. { MP_ROM_QSTR(MP_QSTR_mem_write), MP_ROM_PTR(&pyb_i2c_mem_write_obj) },
  924. // class constants
  925. /// \constant MASTER - for initialising the bus to master mode
  926. /// \constant SLAVE - for initialising the bus to slave mode
  927. { MP_ROM_QSTR(MP_QSTR_MASTER), MP_ROM_INT(PYB_I2C_MASTER) },
  928. { MP_ROM_QSTR(MP_QSTR_SLAVE), MP_ROM_INT(PYB_I2C_SLAVE) },
  929. };
  930. STATIC MP_DEFINE_CONST_DICT(pyb_i2c_locals_dict, pyb_i2c_locals_dict_table);
  931. const mp_obj_type_t pyb_i2c_type = {
  932. { &mp_type_type },
  933. .name = MP_QSTR_I2C,
  934. .print = pyb_i2c_print,
  935. .make_new = pyb_i2c_make_new,
  936. .locals_dict = (mp_obj_dict_t*)&pyb_i2c_locals_dict,
  937. };
  938. #endif // MICROPY_PY_PYB_LEGACY && MICROPY_HW_ENABLE_HW_I2C