uart.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  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 <stdarg.h>
  29. #include "py/runtime.h"
  30. #include "py/stream.h"
  31. #include "py/mperrno.h"
  32. #include "py/mphal.h"
  33. #include "lib/utils/interrupt_char.h"
  34. #include "uart.h"
  35. #include "irq.h"
  36. #include "pendsv.h"
  37. /// \moduleref pyb
  38. /// \class UART - duplex serial communication bus
  39. ///
  40. /// UART implements the standard UART/USART duplex serial communications protocol. At
  41. /// the physical level it consists of 2 lines: RX and TX. The unit of communication
  42. /// is a character (not to be confused with a string character) which can be 8 or 9
  43. /// bits wide.
  44. ///
  45. /// UART objects can be created and initialised using:
  46. ///
  47. /// from pyb import UART
  48. ///
  49. /// uart = UART(1, 9600) # init with given baudrate
  50. /// uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters
  51. ///
  52. /// Bits can be 8 or 9. Parity can be None, 0 (even) or 1 (odd). Stop can be 1 or 2.
  53. ///
  54. /// A UART object acts like a stream object and reading and writing is done
  55. /// using the standard stream methods:
  56. ///
  57. /// uart.read(10) # read 10 characters, returns a bytes object
  58. /// uart.read() # read all available characters
  59. /// uart.readline() # read a line
  60. /// uart.readinto(buf) # read and store into the given buffer
  61. /// uart.write('abc') # write the 3 characters
  62. ///
  63. /// Individual characters can be read/written using:
  64. ///
  65. /// uart.readchar() # read 1 character and returns it as an integer
  66. /// uart.writechar(42) # write 1 character
  67. ///
  68. /// To check if there is anything to be read, use:
  69. ///
  70. /// uart.any() # returns True if any characters waiting
  71. #define CHAR_WIDTH_8BIT (0)
  72. #define CHAR_WIDTH_9BIT (1)
  73. struct _pyb_uart_obj_t {
  74. mp_obj_base_t base;
  75. UART_HandleTypeDef uart; // this is 17 words big
  76. IRQn_Type irqn;
  77. pyb_uart_t uart_id : 8;
  78. bool is_enabled : 1;
  79. bool attached_to_repl; // whether the UART is attached to REPL
  80. byte char_width; // 0 for 7,8 bit chars, 1 for 9 bit chars
  81. uint16_t char_mask; // 0x7f for 7 bit, 0xff for 8 bit, 0x1ff for 9 bit
  82. uint16_t timeout; // timeout waiting for first char
  83. uint16_t timeout_char; // timeout waiting between chars
  84. uint16_t read_buf_len; // len in chars; buf can hold len-1 chars
  85. volatile uint16_t read_buf_head; // indexes first empty slot
  86. uint16_t read_buf_tail; // indexes first full slot (not full if equals head)
  87. byte *read_buf; // byte or uint16_t, depending on char size
  88. };
  89. STATIC mp_obj_t pyb_uart_deinit(mp_obj_t self_in);
  90. extern void NORETURN __fatal_error(const char *msg);
  91. void uart_init0(void) {
  92. #if defined(STM32H7)
  93. RCC_PeriphCLKInitTypeDef RCC_PeriphClkInit = {0};
  94. // Configure USART1/6 clock source
  95. RCC_PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART16;
  96. RCC_PeriphClkInit.Usart16ClockSelection = RCC_USART16CLKSOURCE_D2PCLK2;
  97. if (HAL_RCCEx_PeriphCLKConfig(&RCC_PeriphClkInit) != HAL_OK) {
  98. __fatal_error("HAL_RCCEx_PeriphCLKConfig");
  99. }
  100. // Configure USART2/3/4/5/7/8 clock source
  101. RCC_PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART234578;
  102. RCC_PeriphClkInit.Usart16ClockSelection = RCC_USART234578CLKSOURCE_D2PCLK1;
  103. if (HAL_RCCEx_PeriphCLKConfig(&RCC_PeriphClkInit) != HAL_OK) {
  104. __fatal_error("HAL_RCCEx_PeriphCLKConfig");
  105. }
  106. #endif
  107. for (int i = 0; i < MP_ARRAY_SIZE(MP_STATE_PORT(pyb_uart_obj_all)); i++) {
  108. MP_STATE_PORT(pyb_uart_obj_all)[i] = NULL;
  109. }
  110. }
  111. // unregister all interrupt sources
  112. void uart_deinit(void) {
  113. for (int i = 0; i < MP_ARRAY_SIZE(MP_STATE_PORT(pyb_uart_obj_all)); i++) {
  114. pyb_uart_obj_t *uart_obj = MP_STATE_PORT(pyb_uart_obj_all)[i];
  115. if (uart_obj != NULL) {
  116. pyb_uart_deinit(MP_OBJ_FROM_PTR(uart_obj));
  117. }
  118. }
  119. }
  120. STATIC bool uart_exists(int uart_id) {
  121. if (uart_id > MP_ARRAY_SIZE(MP_STATE_PORT(pyb_uart_obj_all))) {
  122. // safeguard against pyb_uart_obj_all array being configured too small
  123. return false;
  124. }
  125. switch (uart_id) {
  126. #if defined(MICROPY_HW_UART1_TX) && defined(MICROPY_HW_UART1_RX)
  127. case PYB_UART_1: return true;
  128. #endif
  129. #if defined(MICROPY_HW_UART2_TX) && defined(MICROPY_HW_UART2_RX)
  130. case PYB_UART_2: return true;
  131. #endif
  132. #if defined(MICROPY_HW_UART3_TX) && defined(MICROPY_HW_UART3_RX)
  133. case PYB_UART_3: return true;
  134. #endif
  135. #if defined(MICROPY_HW_UART4_TX) && defined(MICROPY_HW_UART4_RX)
  136. case PYB_UART_4: return true;
  137. #endif
  138. #if defined(MICROPY_HW_UART5_TX) && defined(MICROPY_HW_UART5_RX)
  139. case PYB_UART_5: return true;
  140. #endif
  141. #if defined(MICROPY_HW_UART6_TX) && defined(MICROPY_HW_UART6_RX)
  142. case PYB_UART_6: return true;
  143. #endif
  144. #if defined(MICROPY_HW_UART7_TX) && defined(MICROPY_HW_UART7_RX)
  145. case PYB_UART_7: return true;
  146. #endif
  147. #if defined(MICROPY_HW_UART8_TX) && defined(MICROPY_HW_UART8_RX)
  148. case PYB_UART_8: return true;
  149. #endif
  150. default: return false;
  151. }
  152. }
  153. // assumes Init parameters have been set up correctly
  154. STATIC bool uart_init2(pyb_uart_obj_t *uart_obj) {
  155. USART_TypeDef *UARTx;
  156. IRQn_Type irqn;
  157. int uart_unit;
  158. const pin_obj_t *pins[4] = {0};
  159. switch (uart_obj->uart_id) {
  160. #if defined(MICROPY_HW_UART1_TX) && defined(MICROPY_HW_UART1_RX)
  161. case PYB_UART_1:
  162. uart_unit = 1;
  163. UARTx = USART1;
  164. irqn = USART1_IRQn;
  165. pins[0] = MICROPY_HW_UART1_TX;
  166. pins[1] = MICROPY_HW_UART1_RX;
  167. __HAL_RCC_USART1_CLK_ENABLE();
  168. break;
  169. #endif
  170. #if defined(MICROPY_HW_UART2_TX) && defined(MICROPY_HW_UART2_RX)
  171. case PYB_UART_2:
  172. uart_unit = 2;
  173. UARTx = USART2;
  174. irqn = USART2_IRQn;
  175. pins[0] = MICROPY_HW_UART2_TX;
  176. pins[1] = MICROPY_HW_UART2_RX;
  177. #if defined(MICROPY_HW_UART2_RTS)
  178. if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_RTS) {
  179. pins[2] = MICROPY_HW_UART2_RTS;
  180. }
  181. #endif
  182. #if defined(MICROPY_HW_UART2_CTS)
  183. if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS) {
  184. pins[3] = MICROPY_HW_UART2_CTS;
  185. }
  186. #endif
  187. __HAL_RCC_USART2_CLK_ENABLE();
  188. break;
  189. #endif
  190. #if defined(MICROPY_HW_UART3_TX) && defined(MICROPY_HW_UART3_RX)
  191. case PYB_UART_3:
  192. uart_unit = 3;
  193. UARTx = USART3;
  194. irqn = USART3_IRQn;
  195. pins[0] = MICROPY_HW_UART3_TX;
  196. pins[1] = MICROPY_HW_UART3_RX;
  197. #if defined(MICROPY_HW_UART3_RTS)
  198. if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_RTS) {
  199. pins[2] = MICROPY_HW_UART3_RTS;
  200. }
  201. #endif
  202. #if defined(MICROPY_HW_UART3_CTS)
  203. if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS) {
  204. pins[3] = MICROPY_HW_UART3_CTS;
  205. }
  206. #endif
  207. __HAL_RCC_USART3_CLK_ENABLE();
  208. break;
  209. #endif
  210. #if defined(MICROPY_HW_UART4_TX) && defined(MICROPY_HW_UART4_RX)
  211. case PYB_UART_4:
  212. uart_unit = 4;
  213. UARTx = UART4;
  214. irqn = UART4_IRQn;
  215. pins[0] = MICROPY_HW_UART4_TX;
  216. pins[1] = MICROPY_HW_UART4_RX;
  217. __HAL_RCC_UART4_CLK_ENABLE();
  218. break;
  219. #endif
  220. #if defined(MICROPY_HW_UART5_TX) && defined(MICROPY_HW_UART5_RX)
  221. case PYB_UART_5:
  222. uart_unit = 5;
  223. UARTx = UART5;
  224. irqn = UART5_IRQn;
  225. pins[0] = MICROPY_HW_UART5_TX;
  226. pins[1] = MICROPY_HW_UART5_RX;
  227. __HAL_RCC_UART5_CLK_ENABLE();
  228. break;
  229. #endif
  230. #if defined(MICROPY_HW_UART6_TX) && defined(MICROPY_HW_UART6_RX)
  231. case PYB_UART_6:
  232. uart_unit = 6;
  233. UARTx = USART6;
  234. irqn = USART6_IRQn;
  235. pins[0] = MICROPY_HW_UART6_TX;
  236. pins[1] = MICROPY_HW_UART6_RX;
  237. #if defined(MICROPY_HW_UART6_RTS)
  238. if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_RTS) {
  239. pins[2] = MICROPY_HW_UART6_RTS;
  240. }
  241. #endif
  242. #if defined(MICROPY_HW_UART6_CTS)
  243. if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS) {
  244. pins[3] = MICROPY_HW_UART6_CTS;
  245. }
  246. #endif
  247. __HAL_RCC_USART6_CLK_ENABLE();
  248. break;
  249. #endif
  250. #if defined(MICROPY_HW_UART7_TX) && defined(MICROPY_HW_UART7_RX)
  251. case PYB_UART_7:
  252. uart_unit = 7;
  253. UARTx = UART7;
  254. irqn = UART7_IRQn;
  255. pins[0] = MICROPY_HW_UART7_TX;
  256. pins[1] = MICROPY_HW_UART7_RX;
  257. __HAL_RCC_UART7_CLK_ENABLE();
  258. break;
  259. #endif
  260. #if defined(MICROPY_HW_UART8_TX) && defined(MICROPY_HW_UART8_RX)
  261. case PYB_UART_8:
  262. uart_unit = 8;
  263. #if defined(STM32F0)
  264. UARTx = USART8;
  265. irqn = USART3_8_IRQn;
  266. __HAL_RCC_USART8_CLK_ENABLE();
  267. #else
  268. UARTx = UART8;
  269. irqn = UART8_IRQn;
  270. __HAL_RCC_UART8_CLK_ENABLE();
  271. #endif
  272. pins[0] = MICROPY_HW_UART8_TX;
  273. pins[1] = MICROPY_HW_UART8_RX;
  274. break;
  275. #endif
  276. default:
  277. // UART does not exist or is not configured for this board
  278. return false;
  279. }
  280. uint32_t mode = MP_HAL_PIN_MODE_ALT;
  281. uint32_t pull = MP_HAL_PIN_PULL_UP;
  282. for (uint i = 0; i < 4; i++) {
  283. if (pins[i] != NULL) {
  284. bool ret = mp_hal_pin_config_alt(pins[i], mode, pull, AF_FN_UART, uart_unit);
  285. if (!ret) {
  286. return false;
  287. }
  288. }
  289. }
  290. uart_obj->irqn = irqn;
  291. uart_obj->uart.Instance = UARTx;
  292. // init UARTx
  293. HAL_UART_Init(&uart_obj->uart);
  294. uart_obj->is_enabled = true;
  295. uart_obj->attached_to_repl = false;
  296. return true;
  297. }
  298. void uart_attach_to_repl(pyb_uart_obj_t *self, bool attached) {
  299. self->attached_to_repl = attached;
  300. }
  301. /* obsolete and unused
  302. bool uart_init(pyb_uart_obj_t *uart_obj, uint32_t baudrate) {
  303. UART_HandleTypeDef *uh = &uart_obj->uart;
  304. memset(uh, 0, sizeof(*uh));
  305. uh->Init.BaudRate = baudrate;
  306. uh->Init.WordLength = UART_WORDLENGTH_8B;
  307. uh->Init.StopBits = UART_STOPBITS_1;
  308. uh->Init.Parity = UART_PARITY_NONE;
  309. uh->Init.Mode = UART_MODE_TX_RX;
  310. uh->Init.HwFlowCtl = UART_HWCONTROL_NONE;
  311. uh->Init.OverSampling = UART_OVERSAMPLING_16;
  312. return uart_init2(uart_obj);
  313. }
  314. */
  315. mp_uint_t uart_rx_any(pyb_uart_obj_t *self) {
  316. int buffer_bytes = self->read_buf_head - self->read_buf_tail;
  317. if (buffer_bytes < 0) {
  318. return buffer_bytes + self->read_buf_len;
  319. } else if (buffer_bytes > 0) {
  320. return buffer_bytes;
  321. } else {
  322. return __HAL_UART_GET_FLAG(&self->uart, UART_FLAG_RXNE) != RESET;
  323. }
  324. }
  325. // Waits at most timeout milliseconds for at least 1 char to become ready for
  326. // reading (from buf or for direct reading).
  327. // Returns true if something available, false if not.
  328. STATIC bool uart_rx_wait(pyb_uart_obj_t *self, uint32_t timeout) {
  329. uint32_t start = HAL_GetTick();
  330. for (;;) {
  331. if (self->read_buf_tail != self->read_buf_head || __HAL_UART_GET_FLAG(&self->uart, UART_FLAG_RXNE) != RESET) {
  332. return true; // have at least 1 char ready for reading
  333. }
  334. if (HAL_GetTick() - start >= timeout) {
  335. return false; // timeout
  336. }
  337. MICROPY_EVENT_POLL_HOOK
  338. }
  339. }
  340. // assumes there is a character available
  341. int uart_rx_char(pyb_uart_obj_t *self) {
  342. if (self->read_buf_tail != self->read_buf_head) {
  343. // buffering via IRQ
  344. int data;
  345. if (self->char_width == CHAR_WIDTH_9BIT) {
  346. data = ((uint16_t*)self->read_buf)[self->read_buf_tail];
  347. } else {
  348. data = self->read_buf[self->read_buf_tail];
  349. }
  350. self->read_buf_tail = (self->read_buf_tail + 1) % self->read_buf_len;
  351. if (__HAL_UART_GET_FLAG(&self->uart, UART_FLAG_RXNE) != RESET) {
  352. // UART was stalled by flow ctrl: re-enable IRQ now we have room in buffer
  353. __HAL_UART_ENABLE_IT(&self->uart, UART_IT_RXNE);
  354. }
  355. return data;
  356. } else {
  357. // no buffering
  358. #if defined(STM32F0) || defined(STM32F7) || defined(STM32L4) || defined(STM32H7)
  359. return self->uart.Instance->RDR & self->char_mask;
  360. #else
  361. return self->uart.Instance->DR & self->char_mask;
  362. #endif
  363. }
  364. }
  365. // Waits at most timeout milliseconds for TX register to become empty.
  366. // Returns true if can write, false if can't.
  367. STATIC bool uart_tx_wait(pyb_uart_obj_t *self, uint32_t timeout) {
  368. uint32_t start = HAL_GetTick();
  369. for (;;) {
  370. if (__HAL_UART_GET_FLAG(&self->uart, UART_FLAG_TXE)) {
  371. return true; // tx register is empty
  372. }
  373. if (HAL_GetTick() - start >= timeout) {
  374. return false; // timeout
  375. }
  376. MICROPY_EVENT_POLL_HOOK
  377. }
  378. }
  379. // Waits at most timeout milliseconds for UART flag to be set.
  380. // Returns true if flag is/was set, false on timeout.
  381. STATIC bool uart_wait_flag_set(pyb_uart_obj_t *self, uint32_t flag, uint32_t timeout) {
  382. // Note: we don't use WFI to idle in this loop because UART tx doesn't generate
  383. // an interrupt and the flag can be set quickly if the baudrate is large.
  384. uint32_t start = HAL_GetTick();
  385. for (;;) {
  386. if (__HAL_UART_GET_FLAG(&self->uart, flag)) {
  387. return true;
  388. }
  389. if (timeout == 0 || HAL_GetTick() - start >= timeout) {
  390. return false; // timeout
  391. }
  392. }
  393. }
  394. // src - a pointer to the data to send (16-bit aligned for 9-bit chars)
  395. // num_chars - number of characters to send (9-bit chars count for 2 bytes from src)
  396. // *errcode - returns 0 for success, MP_Exxx on error
  397. // returns the number of characters sent (valid even if there was an error)
  398. STATIC size_t uart_tx_data(pyb_uart_obj_t *self, const void *src_in, size_t num_chars, int *errcode) {
  399. if (num_chars == 0) {
  400. *errcode = 0;
  401. return 0;
  402. }
  403. uint32_t timeout;
  404. if (self->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS) {
  405. // CTS can hold off transmission for an arbitrarily long time. Apply
  406. // the overall timeout rather than the character timeout.
  407. timeout = self->timeout;
  408. } else {
  409. // The timeout specified here is for waiting for the TX data register to
  410. // become empty (ie between chars), as well as for the final char to be
  411. // completely transferred. The default value for timeout_char is long
  412. // enough for 1 char, but we need to double it to wait for the last char
  413. // to be transferred to the data register, and then to be transmitted.
  414. timeout = 2 * self->timeout_char;
  415. }
  416. const uint8_t *src = (const uint8_t*)src_in;
  417. size_t num_tx = 0;
  418. USART_TypeDef *uart = self->uart.Instance;
  419. while (num_tx < num_chars) {
  420. if (!uart_wait_flag_set(self, UART_FLAG_TXE, timeout)) {
  421. *errcode = MP_ETIMEDOUT;
  422. return num_tx;
  423. }
  424. uint32_t data;
  425. if (self->char_width == CHAR_WIDTH_9BIT) {
  426. data = *((uint16_t*)src) & 0x1ff;
  427. src += 2;
  428. } else {
  429. data = *src++;
  430. }
  431. #if defined(STM32F4)
  432. uart->DR = data;
  433. #else
  434. uart->TDR = data;
  435. #endif
  436. ++num_tx;
  437. }
  438. // wait for the UART frame to complete
  439. if (!uart_wait_flag_set(self, UART_FLAG_TC, timeout)) {
  440. *errcode = MP_ETIMEDOUT;
  441. return num_tx;
  442. }
  443. *errcode = 0;
  444. return num_tx;
  445. }
  446. void uart_tx_strn(pyb_uart_obj_t *uart_obj, const char *str, uint len) {
  447. int errcode;
  448. uart_tx_data(uart_obj, str, len, &errcode);
  449. }
  450. // this IRQ handler is set up to handle RXNE interrupts only
  451. void uart_irq_handler(mp_uint_t uart_id) {
  452. // get the uart object
  453. pyb_uart_obj_t *self = MP_STATE_PORT(pyb_uart_obj_all)[uart_id - 1];
  454. if (self == NULL) {
  455. // UART object has not been set, so we can't do anything, not
  456. // even disable the IRQ. This should never happen.
  457. return;
  458. }
  459. if (__HAL_UART_GET_FLAG(&self->uart, UART_FLAG_RXNE) != RESET) {
  460. if (self->read_buf_len != 0) {
  461. uint16_t next_head = (self->read_buf_head + 1) % self->read_buf_len;
  462. if (next_head != self->read_buf_tail) {
  463. // only read data if room in buf
  464. #if defined(STM32F0) || defined(STM32F7) || defined(STM32L4) || defined(STM32H7)
  465. int data = self->uart.Instance->RDR; // clears UART_FLAG_RXNE
  466. #else
  467. int data = self->uart.Instance->DR; // clears UART_FLAG_RXNE
  468. #endif
  469. data &= self->char_mask;
  470. // Handle interrupt coming in on a UART REPL
  471. if (self->attached_to_repl && data == mp_interrupt_char) {
  472. pendsv_kbd_intr();
  473. return;
  474. }
  475. if (self->char_width == CHAR_WIDTH_9BIT) {
  476. ((uint16_t*)self->read_buf)[self->read_buf_head] = data;
  477. } else {
  478. self->read_buf[self->read_buf_head] = data;
  479. }
  480. self->read_buf_head = next_head;
  481. } else { // No room: leave char in buf, disable interrupt
  482. __HAL_UART_DISABLE_IT(&self->uart, UART_IT_RXNE);
  483. }
  484. }
  485. }
  486. }
  487. /******************************************************************************/
  488. /* MicroPython bindings */
  489. STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  490. pyb_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
  491. if (!self->is_enabled) {
  492. mp_printf(print, "UART(%u)", self->uart_id);
  493. } else {
  494. mp_int_t bits;
  495. switch (self->uart.Init.WordLength) {
  496. #ifdef UART_WORDLENGTH_7B
  497. case UART_WORDLENGTH_7B: bits = 7; break;
  498. #endif
  499. case UART_WORDLENGTH_8B: bits = 8; break;
  500. case UART_WORDLENGTH_9B: default: bits = 9; break;
  501. }
  502. if (self->uart.Init.Parity != UART_PARITY_NONE) {
  503. bits -= 1;
  504. }
  505. mp_printf(print, "UART(%u, baudrate=%u, bits=%u, parity=",
  506. self->uart_id, self->uart.Init.BaudRate, bits);
  507. if (self->uart.Init.Parity == UART_PARITY_NONE) {
  508. mp_print_str(print, "None");
  509. } else {
  510. mp_printf(print, "%u", self->uart.Init.Parity == UART_PARITY_EVEN ? 0 : 1);
  511. }
  512. if (self->uart.Init.HwFlowCtl) {
  513. mp_printf(print, ", flow=");
  514. if (self->uart.Init.HwFlowCtl & UART_HWCONTROL_RTS) {
  515. mp_printf(print, "RTS%s", self->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS ? "|" : "");
  516. }
  517. if (self->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS) {
  518. mp_printf(print, "CTS");
  519. }
  520. }
  521. mp_printf(print, ", stop=%u, timeout=%u, timeout_char=%u, read_buf_len=%u)",
  522. self->uart.Init.StopBits == UART_STOPBITS_1 ? 1 : 2,
  523. self->timeout, self->timeout_char,
  524. self->read_buf_len == 0 ? 0 : self->read_buf_len - 1); // -1 to adjust for usable length of buffer
  525. }
  526. }
  527. /// \method init(baudrate, bits=8, parity=None, stop=1, *, timeout=1000, timeout_char=0, flow=0, read_buf_len=64)
  528. ///
  529. /// Initialise the UART bus with the given parameters:
  530. ///
  531. /// - `baudrate` is the clock rate.
  532. /// - `bits` is the number of bits per byte, 7, 8 or 9.
  533. /// - `parity` is the parity, `None`, 0 (even) or 1 (odd).
  534. /// - `stop` is the number of stop bits, 1 or 2.
  535. /// - `timeout` is the timeout in milliseconds to wait for the first character.
  536. /// - `timeout_char` is the timeout in milliseconds to wait between characters.
  537. /// - `flow` is RTS | CTS where RTS == 256, CTS == 512
  538. /// - `read_buf_len` is the character length of the read buffer (0 to disable).
  539. STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  540. static const mp_arg_t allowed_args[] = {
  541. { MP_QSTR_baudrate, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 9600} },
  542. { MP_QSTR_bits, MP_ARG_INT, {.u_int = 8} },
  543. { MP_QSTR_parity, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  544. { MP_QSTR_stop, MP_ARG_INT, {.u_int = 1} },
  545. { MP_QSTR_flow, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = UART_HWCONTROL_NONE} },
  546. { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} },
  547. { MP_QSTR_timeout_char, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
  548. { MP_QSTR_read_buf_len, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 64} },
  549. };
  550. // parse args
  551. struct {
  552. mp_arg_val_t baudrate, bits, parity, stop, flow, timeout, timeout_char, read_buf_len;
  553. } args;
  554. mp_arg_parse_all(n_args, pos_args, kw_args,
  555. MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
  556. // set the UART configuration values
  557. memset(&self->uart, 0, sizeof(self->uart));
  558. UART_InitTypeDef *init = &self->uart.Init;
  559. // baudrate
  560. init->BaudRate = args.baudrate.u_int;
  561. // parity
  562. mp_int_t bits = args.bits.u_int;
  563. if (args.parity.u_obj == mp_const_none) {
  564. init->Parity = UART_PARITY_NONE;
  565. } else {
  566. mp_int_t parity = mp_obj_get_int(args.parity.u_obj);
  567. init->Parity = (parity & 1) ? UART_PARITY_ODD : UART_PARITY_EVEN;
  568. bits += 1; // STs convention has bits including parity
  569. }
  570. // number of bits
  571. if (bits == 8) {
  572. init->WordLength = UART_WORDLENGTH_8B;
  573. } else if (bits == 9) {
  574. init->WordLength = UART_WORDLENGTH_9B;
  575. #ifdef UART_WORDLENGTH_7B
  576. } else if (bits == 7) {
  577. init->WordLength = UART_WORDLENGTH_7B;
  578. #endif
  579. } else {
  580. mp_raise_ValueError("unsupported combination of bits and parity");
  581. }
  582. // stop bits
  583. switch (args.stop.u_int) {
  584. case 1: init->StopBits = UART_STOPBITS_1; break;
  585. default: init->StopBits = UART_STOPBITS_2; break;
  586. }
  587. // flow control
  588. init->HwFlowCtl = args.flow.u_int;
  589. // extra config (not yet configurable)
  590. init->Mode = UART_MODE_TX_RX;
  591. init->OverSampling = UART_OVERSAMPLING_16;
  592. // init UART (if it fails, it's because the port doesn't exist)
  593. if (!uart_init2(self)) {
  594. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%d) doesn't exist", self->uart_id));
  595. }
  596. // set timeout
  597. self->timeout = args.timeout.u_int;
  598. // set timeout_char
  599. // make sure it is at least as long as a whole character (13 bits to be safe)
  600. // minimum value is 2ms because sys-tick has a resolution of only 1ms
  601. self->timeout_char = args.timeout_char.u_int;
  602. uint32_t min_timeout_char = 13000 / init->BaudRate + 2;
  603. if (self->timeout_char < min_timeout_char) {
  604. self->timeout_char = min_timeout_char;
  605. }
  606. // setup the read buffer
  607. m_del(byte, self->read_buf, self->read_buf_len << self->char_width);
  608. if (init->WordLength == UART_WORDLENGTH_9B && init->Parity == UART_PARITY_NONE) {
  609. self->char_mask = 0x1ff;
  610. self->char_width = CHAR_WIDTH_9BIT;
  611. } else {
  612. if (init->WordLength == UART_WORDLENGTH_9B || init->Parity == UART_PARITY_NONE) {
  613. self->char_mask = 0xff;
  614. } else {
  615. self->char_mask = 0x7f;
  616. }
  617. self->char_width = CHAR_WIDTH_8BIT;
  618. }
  619. self->read_buf_head = 0;
  620. self->read_buf_tail = 0;
  621. if (args.read_buf_len.u_int <= 0) {
  622. // no read buffer
  623. self->read_buf_len = 0;
  624. self->read_buf = NULL;
  625. HAL_NVIC_DisableIRQ(self->irqn);
  626. __HAL_UART_DISABLE_IT(&self->uart, UART_IT_RXNE);
  627. } else {
  628. // read buffer using interrupts
  629. self->read_buf_len = args.read_buf_len.u_int + 1; // +1 to adjust for usable length of buffer
  630. self->read_buf = m_new(byte, self->read_buf_len << self->char_width);
  631. __HAL_UART_ENABLE_IT(&self->uart, UART_IT_RXNE);
  632. NVIC_SetPriority(IRQn_NONNEG(self->irqn), IRQ_PRI_UART);
  633. HAL_NVIC_EnableIRQ(self->irqn);
  634. }
  635. // compute actual baudrate that was configured
  636. // (this formula assumes UART_OVERSAMPLING_16)
  637. uint32_t actual_baudrate = 0;
  638. #if defined(STM32F0)
  639. actual_baudrate = HAL_RCC_GetPCLK1Freq();
  640. #elif defined(STM32F7) || defined(STM32H7)
  641. UART_ClockSourceTypeDef clocksource = UART_CLOCKSOURCE_UNDEFINED;
  642. UART_GETCLOCKSOURCE(&self->uart, clocksource);
  643. switch (clocksource) {
  644. #if defined(STM32H7)
  645. case UART_CLOCKSOURCE_D2PCLK1: actual_baudrate = HAL_RCC_GetPCLK1Freq(); break;
  646. case UART_CLOCKSOURCE_D3PCLK1: actual_baudrate = HAL_RCC_GetPCLK1Freq(); break;
  647. case UART_CLOCKSOURCE_D2PCLK2: actual_baudrate = HAL_RCC_GetPCLK2Freq(); break;
  648. #else
  649. case UART_CLOCKSOURCE_PCLK1: actual_baudrate = HAL_RCC_GetPCLK1Freq(); break;
  650. case UART_CLOCKSOURCE_PCLK2: actual_baudrate = HAL_RCC_GetPCLK2Freq(); break;
  651. case UART_CLOCKSOURCE_SYSCLK: actual_baudrate = HAL_RCC_GetSysClockFreq(); break;
  652. #endif
  653. #if defined(STM32H7)
  654. case UART_CLOCKSOURCE_CSI: actual_baudrate = CSI_VALUE; break;
  655. #endif
  656. case UART_CLOCKSOURCE_HSI: actual_baudrate = HSI_VALUE; break;
  657. case UART_CLOCKSOURCE_LSE: actual_baudrate = LSE_VALUE; break;
  658. #if defined(STM32H7)
  659. case UART_CLOCKSOURCE_PLL2:
  660. case UART_CLOCKSOURCE_PLL3:
  661. #endif
  662. case UART_CLOCKSOURCE_UNDEFINED: break;
  663. }
  664. #else
  665. if (self->uart.Instance == USART1
  666. #if defined(USART6)
  667. || self->uart.Instance == USART6
  668. #endif
  669. ) {
  670. actual_baudrate = HAL_RCC_GetPCLK2Freq();
  671. } else {
  672. actual_baudrate = HAL_RCC_GetPCLK1Freq();
  673. }
  674. #endif
  675. actual_baudrate /= self->uart.Instance->BRR;
  676. // check we could set the baudrate within 5%
  677. uint32_t baudrate_diff;
  678. if (actual_baudrate > init->BaudRate) {
  679. baudrate_diff = actual_baudrate - init->BaudRate;
  680. } else {
  681. baudrate_diff = init->BaudRate - actual_baudrate;
  682. }
  683. init->BaudRate = actual_baudrate; // remember actual baudrate for printing
  684. if (20 * baudrate_diff > init->BaudRate) {
  685. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "set baudrate %d is not within 5%% of desired value", actual_baudrate));
  686. }
  687. return mp_const_none;
  688. }
  689. /// \classmethod \constructor(bus, ...)
  690. ///
  691. /// Construct a UART object on the given bus. `bus` can be 1-6, or 'XA', 'XB', 'YA', or 'YB'.
  692. /// With no additional parameters, the UART object is created but not
  693. /// initialised (it has the settings from the last initialisation of
  694. /// the bus, if any). If extra arguments are given, the bus is initialised.
  695. /// See `init` for parameters of initialisation.
  696. ///
  697. /// The physical pins of the UART busses are:
  698. ///
  699. /// - `UART(4)` is on `XA`: `(TX, RX) = (X1, X2) = (PA0, PA1)`
  700. /// - `UART(1)` is on `XB`: `(TX, RX) = (X9, X10) = (PB6, PB7)`
  701. /// - `UART(6)` is on `YA`: `(TX, RX) = (Y1, Y2) = (PC6, PC7)`
  702. /// - `UART(3)` is on `YB`: `(TX, RX) = (Y9, Y10) = (PB10, PB11)`
  703. /// - `UART(2)` is on: `(TX, RX) = (X3, X4) = (PA2, PA3)`
  704. STATIC mp_obj_t pyb_uart_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  705. // check arguments
  706. mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
  707. // work out port
  708. int uart_id = 0;
  709. if (MP_OBJ_IS_STR(args[0])) {
  710. const char *port = mp_obj_str_get_str(args[0]);
  711. if (0) {
  712. #ifdef MICROPY_HW_UART1_NAME
  713. } else if (strcmp(port, MICROPY_HW_UART1_NAME) == 0) {
  714. uart_id = PYB_UART_1;
  715. #endif
  716. #ifdef MICROPY_HW_UART2_NAME
  717. } else if (strcmp(port, MICROPY_HW_UART2_NAME) == 0) {
  718. uart_id = PYB_UART_2;
  719. #endif
  720. #ifdef MICROPY_HW_UART3_NAME
  721. } else if (strcmp(port, MICROPY_HW_UART3_NAME) == 0) {
  722. uart_id = PYB_UART_3;
  723. #endif
  724. #ifdef MICROPY_HW_UART4_NAME
  725. } else if (strcmp(port, MICROPY_HW_UART4_NAME) == 0) {
  726. uart_id = PYB_UART_4;
  727. #endif
  728. #ifdef MICROPY_HW_UART5_NAME
  729. } else if (strcmp(port, MICROPY_HW_UART5_NAME) == 0) {
  730. uart_id = PYB_UART_5;
  731. #endif
  732. #ifdef MICROPY_HW_UART6_NAME
  733. } else if (strcmp(port, MICROPY_HW_UART6_NAME) == 0) {
  734. uart_id = PYB_UART_6;
  735. #endif
  736. } else {
  737. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%s) doesn't exist", port));
  738. }
  739. } else {
  740. uart_id = mp_obj_get_int(args[0]);
  741. if (!uart_exists(uart_id)) {
  742. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%d) doesn't exist", uart_id));
  743. }
  744. }
  745. pyb_uart_obj_t *self;
  746. if (MP_STATE_PORT(pyb_uart_obj_all)[uart_id - 1] == NULL) {
  747. // create new UART object
  748. self = m_new0(pyb_uart_obj_t, 1);
  749. self->base.type = &pyb_uart_type;
  750. self->uart_id = uart_id;
  751. MP_STATE_PORT(pyb_uart_obj_all)[uart_id - 1] = self;
  752. } else {
  753. // reference existing UART object
  754. self = MP_STATE_PORT(pyb_uart_obj_all)[uart_id - 1];
  755. }
  756. if (n_args > 1 || n_kw > 0) {
  757. // start the peripheral
  758. mp_map_t kw_args;
  759. mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
  760. pyb_uart_init_helper(self, n_args - 1, args + 1, &kw_args);
  761. }
  762. return MP_OBJ_FROM_PTR(self);
  763. }
  764. STATIC mp_obj_t pyb_uart_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
  765. return pyb_uart_init_helper(MP_OBJ_TO_PTR(args[0]), n_args - 1, args + 1, kw_args);
  766. }
  767. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_init_obj, 1, pyb_uart_init);
  768. /// \method deinit()
  769. /// Turn off the UART bus.
  770. STATIC mp_obj_t pyb_uart_deinit(mp_obj_t self_in) {
  771. pyb_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
  772. self->is_enabled = false;
  773. UART_HandleTypeDef *uart = &self->uart;
  774. HAL_UART_DeInit(uart);
  775. if (uart->Instance == USART1) {
  776. HAL_NVIC_DisableIRQ(USART1_IRQn);
  777. __HAL_RCC_USART1_FORCE_RESET();
  778. __HAL_RCC_USART1_RELEASE_RESET();
  779. __HAL_RCC_USART1_CLK_DISABLE();
  780. } else if (uart->Instance == USART2) {
  781. HAL_NVIC_DisableIRQ(USART2_IRQn);
  782. __HAL_RCC_USART2_FORCE_RESET();
  783. __HAL_RCC_USART2_RELEASE_RESET();
  784. __HAL_RCC_USART2_CLK_DISABLE();
  785. #if defined(USART3)
  786. } else if (uart->Instance == USART3) {
  787. #if !defined(STM32F0)
  788. HAL_NVIC_DisableIRQ(USART3_IRQn);
  789. #endif
  790. __HAL_RCC_USART3_FORCE_RESET();
  791. __HAL_RCC_USART3_RELEASE_RESET();
  792. __HAL_RCC_USART3_CLK_DISABLE();
  793. #endif
  794. #if defined(UART4)
  795. } else if (uart->Instance == UART4) {
  796. HAL_NVIC_DisableIRQ(UART4_IRQn);
  797. __HAL_RCC_UART4_FORCE_RESET();
  798. __HAL_RCC_UART4_RELEASE_RESET();
  799. __HAL_RCC_UART4_CLK_DISABLE();
  800. #endif
  801. #if defined(UART5)
  802. } else if (uart->Instance == UART5) {
  803. HAL_NVIC_DisableIRQ(UART5_IRQn);
  804. __HAL_RCC_UART5_FORCE_RESET();
  805. __HAL_RCC_UART5_RELEASE_RESET();
  806. __HAL_RCC_UART5_CLK_DISABLE();
  807. #endif
  808. #if defined(UART6)
  809. } else if (uart->Instance == USART6) {
  810. HAL_NVIC_DisableIRQ(USART6_IRQn);
  811. __HAL_RCC_USART6_FORCE_RESET();
  812. __HAL_RCC_USART6_RELEASE_RESET();
  813. __HAL_RCC_USART6_CLK_DISABLE();
  814. #endif
  815. #if defined(UART7)
  816. } else if (uart->Instance == UART7) {
  817. HAL_NVIC_DisableIRQ(UART7_IRQn);
  818. __HAL_RCC_UART7_FORCE_RESET();
  819. __HAL_RCC_UART7_RELEASE_RESET();
  820. __HAL_RCC_UART7_CLK_DISABLE();
  821. #endif
  822. #if defined(UART8)
  823. } else if (uart->Instance == UART8) {
  824. HAL_NVIC_DisableIRQ(UART8_IRQn);
  825. __HAL_RCC_UART8_FORCE_RESET();
  826. __HAL_RCC_UART8_RELEASE_RESET();
  827. __HAL_RCC_UART8_CLK_DISABLE();
  828. #endif
  829. }
  830. return mp_const_none;
  831. }
  832. STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_deinit_obj, pyb_uart_deinit);
  833. /// \method any()
  834. /// Return `True` if any characters waiting, else `False`.
  835. STATIC mp_obj_t pyb_uart_any(mp_obj_t self_in) {
  836. pyb_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
  837. return MP_OBJ_NEW_SMALL_INT(uart_rx_any(self));
  838. }
  839. STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_any_obj, pyb_uart_any);
  840. /// \method writechar(char)
  841. /// Write a single character on the bus. `char` is an integer to write.
  842. /// Return value: `None`.
  843. STATIC mp_obj_t pyb_uart_writechar(mp_obj_t self_in, mp_obj_t char_in) {
  844. pyb_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
  845. // get the character to write (might be 9 bits)
  846. uint16_t data = mp_obj_get_int(char_in);
  847. // write the character
  848. int errcode;
  849. if (uart_tx_wait(self, self->timeout)) {
  850. uart_tx_data(self, &data, 1, &errcode);
  851. } else {
  852. errcode = MP_ETIMEDOUT;
  853. }
  854. if (errcode != 0) {
  855. mp_raise_OSError(errcode);
  856. }
  857. return mp_const_none;
  858. }
  859. STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_uart_writechar_obj, pyb_uart_writechar);
  860. /// \method readchar()
  861. /// Receive a single character on the bus.
  862. /// Return value: The character read, as an integer. Returns -1 on timeout.
  863. STATIC mp_obj_t pyb_uart_readchar(mp_obj_t self_in) {
  864. pyb_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
  865. if (uart_rx_wait(self, self->timeout)) {
  866. return MP_OBJ_NEW_SMALL_INT(uart_rx_char(self));
  867. } else {
  868. // return -1 on timeout
  869. return MP_OBJ_NEW_SMALL_INT(-1);
  870. }
  871. }
  872. STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_readchar_obj, pyb_uart_readchar);
  873. // uart.sendbreak()
  874. STATIC mp_obj_t pyb_uart_sendbreak(mp_obj_t self_in) {
  875. pyb_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
  876. #if defined(STM32F0) || defined(STM32F7) || defined(STM32L4) || defined(STM32H7)
  877. self->uart.Instance->RQR = USART_RQR_SBKRQ; // write-only register
  878. #else
  879. self->uart.Instance->CR1 |= USART_CR1_SBK;
  880. #endif
  881. return mp_const_none;
  882. }
  883. STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_sendbreak_obj, pyb_uart_sendbreak);
  884. STATIC const mp_rom_map_elem_t pyb_uart_locals_dict_table[] = {
  885. // instance methods
  886. { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_uart_init_obj) },
  887. { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_uart_deinit_obj) },
  888. { MP_ROM_QSTR(MP_QSTR_any), MP_ROM_PTR(&pyb_uart_any_obj) },
  889. /// \method read([nbytes])
  890. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  891. /// \method readline()
  892. { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj)},
  893. /// \method readinto(buf[, nbytes])
  894. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  895. /// \method write(buf)
  896. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  897. { MP_ROM_QSTR(MP_QSTR_writechar), MP_ROM_PTR(&pyb_uart_writechar_obj) },
  898. { MP_ROM_QSTR(MP_QSTR_readchar), MP_ROM_PTR(&pyb_uart_readchar_obj) },
  899. { MP_ROM_QSTR(MP_QSTR_sendbreak), MP_ROM_PTR(&pyb_uart_sendbreak_obj) },
  900. // class constants
  901. { MP_ROM_QSTR(MP_QSTR_RTS), MP_ROM_INT(UART_HWCONTROL_RTS) },
  902. { MP_ROM_QSTR(MP_QSTR_CTS), MP_ROM_INT(UART_HWCONTROL_CTS) },
  903. };
  904. STATIC MP_DEFINE_CONST_DICT(pyb_uart_locals_dict, pyb_uart_locals_dict_table);
  905. STATIC mp_uint_t pyb_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, int *errcode) {
  906. pyb_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
  907. byte *buf = buf_in;
  908. // check that size is a multiple of character width
  909. if (size & self->char_width) {
  910. *errcode = MP_EIO;
  911. return MP_STREAM_ERROR;
  912. }
  913. // convert byte size to char size
  914. size >>= self->char_width;
  915. // make sure we want at least 1 char
  916. if (size == 0) {
  917. return 0;
  918. }
  919. // wait for first char to become available
  920. if (!uart_rx_wait(self, self->timeout)) {
  921. // return EAGAIN error to indicate non-blocking (then read() method returns None)
  922. *errcode = MP_EAGAIN;
  923. return MP_STREAM_ERROR;
  924. }
  925. // read the data
  926. byte *orig_buf = buf;
  927. for (;;) {
  928. int data = uart_rx_char(self);
  929. if (self->char_width == CHAR_WIDTH_9BIT) {
  930. *(uint16_t*)buf = data;
  931. buf += 2;
  932. } else {
  933. *buf++ = data;
  934. }
  935. if (--size == 0 || !uart_rx_wait(self, self->timeout_char)) {
  936. // return number of bytes read
  937. return buf - orig_buf;
  938. }
  939. }
  940. }
  941. STATIC mp_uint_t pyb_uart_write(mp_obj_t self_in, const void *buf_in, mp_uint_t size, int *errcode) {
  942. pyb_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
  943. const byte *buf = buf_in;
  944. // check that size is a multiple of character width
  945. if (size & self->char_width) {
  946. *errcode = MP_EIO;
  947. return MP_STREAM_ERROR;
  948. }
  949. // wait to be able to write the first character. EAGAIN causes write to return None
  950. if (!uart_tx_wait(self, self->timeout)) {
  951. *errcode = MP_EAGAIN;
  952. return MP_STREAM_ERROR;
  953. }
  954. // write the data
  955. size_t num_tx = uart_tx_data(self, buf, size >> self->char_width, errcode);
  956. if (*errcode == 0 || *errcode == MP_ETIMEDOUT) {
  957. // return number of bytes written, even if there was a timeout
  958. return num_tx << self->char_width;
  959. } else {
  960. return MP_STREAM_ERROR;
  961. }
  962. }
  963. STATIC mp_uint_t pyb_uart_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) {
  964. pyb_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
  965. mp_uint_t ret;
  966. if (request == MP_STREAM_POLL) {
  967. uintptr_t flags = arg;
  968. ret = 0;
  969. if ((flags & MP_STREAM_POLL_RD) && uart_rx_any(self)) {
  970. ret |= MP_STREAM_POLL_RD;
  971. }
  972. if ((flags & MP_STREAM_POLL_WR) && __HAL_UART_GET_FLAG(&self->uart, UART_FLAG_TXE)) {
  973. ret |= MP_STREAM_POLL_WR;
  974. }
  975. } else {
  976. *errcode = MP_EINVAL;
  977. ret = MP_STREAM_ERROR;
  978. }
  979. return ret;
  980. }
  981. STATIC const mp_stream_p_t uart_stream_p = {
  982. .read = pyb_uart_read,
  983. .write = pyb_uart_write,
  984. .ioctl = pyb_uart_ioctl,
  985. .is_text = false,
  986. };
  987. const mp_obj_type_t pyb_uart_type = {
  988. { &mp_type_type },
  989. .name = MP_QSTR_UART,
  990. .print = pyb_uart_print,
  991. .make_new = pyb_uart_make_new,
  992. .getiter = mp_identity_getiter,
  993. .iternext = mp_stream_unbuffered_iter,
  994. .protocol = &uart_stream_p,
  995. .locals_dict = (mp_obj_dict_t*)&pyb_uart_locals_dict,
  996. };