uart.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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 "bufhelper.h"
  30. #include "uart.h"
  31. /// \moduleref pyb
  32. /// \class UART - duplex serial communication bus
  33. ///
  34. /// UART implements the standard UART/USART duplex serial communications protocol. At
  35. /// the physical level it consists of 2 lines: RX and TX.
  36. ///
  37. /// See usage model of I2C. UART is very similar. Main difference is
  38. /// parameters to init the UART bus:
  39. ///
  40. /// from pyb import UART
  41. ///
  42. /// uart = UART(1, 9600) # init with given baudrate
  43. /// uart.init(9600, bits=8, stop=1, parity=None) # init with given parameters
  44. ///
  45. /// Bits can be 8 or 9, stop can be 1 or 2, parity can be None, 0 (even), 1 (odd).
  46. ///
  47. /// Extra method:
  48. ///
  49. /// uart.any() # returns True if any characters waiting
  50. struct _pyb_uart_obj_t {
  51. mp_obj_base_t base;
  52. pyb_uart_t uart_id;
  53. bool is_enabled;
  54. // UART_HandleTypeDef uart;
  55. };
  56. pyb_uart_obj_t *pyb_uart_global_debug = NULL;
  57. // assumes Init parameters have been set up correctly
  58. bool uart_init2(pyb_uart_obj_t *uart_obj) {
  59. #if 0
  60. USART_TypeDef *UARTx = NULL;
  61. uint32_t GPIO_Pin = 0;
  62. uint8_t GPIO_AF_UARTx = 0;
  63. GPIO_TypeDef* GPIO_Port = NULL;
  64. switch (uart_obj->uart_id) {
  65. // USART1 is on PA9/PA10 (CK on PA8), PB6/PB7
  66. case PYB_UART_1:
  67. UARTx = USART1;
  68. GPIO_AF_UARTx = GPIO_AF7_USART1;
  69. #if defined (PYBV4) || defined(PYBV10)
  70. GPIO_Port = GPIOB;
  71. GPIO_Pin = GPIO_PIN_6 | GPIO_PIN_7;
  72. #else
  73. GPIO_Port = GPIOA;
  74. GPIO_Pin = GPIO_PIN_9 | GPIO_PIN_10;
  75. #endif
  76. __USART1_CLK_ENABLE();
  77. break;
  78. // USART2 is on PA2/PA3 (CK on PA4), PD5/PD6 (CK on PD7)
  79. case PYB_UART_2:
  80. UARTx = USART2;
  81. GPIO_AF_UARTx = GPIO_AF7_USART2;
  82. GPIO_Port = GPIOA;
  83. GPIO_Pin = GPIO_PIN_2 | GPIO_PIN_3;
  84. __USART2_CLK_ENABLE();
  85. break;
  86. // USART3 is on PB10/PB11 (CK on PB12), PC10/PC11 (CK on PC12), PD8/PD9 (CK on PD10)
  87. case PYB_UART_3:
  88. UARTx = USART3;
  89. GPIO_AF_UARTx = GPIO_AF7_USART3;
  90. #if defined(PYBV3) || defined(PYBV4) | defined(PYBV10)
  91. GPIO_Port = GPIOB;
  92. GPIO_Pin = GPIO_PIN_10 | GPIO_PIN_11;
  93. #else
  94. GPIO_Port = GPIOD;
  95. GPIO_Pin = GPIO_PIN_8 | GPIO_PIN_9;
  96. #endif
  97. __USART3_CLK_ENABLE();
  98. break;
  99. // UART4 is on PA0/PA1, PC10/PC11
  100. case PYB_UART_4:
  101. UARTx = UART4;
  102. GPIO_AF_UARTx = GPIO_AF8_UART4;
  103. GPIO_Port = GPIOA;
  104. GPIO_Pin = GPIO_PIN_0 | GPIO_PIN_1;
  105. __UART4_CLK_ENABLE();
  106. break;
  107. // USART6 is on PC6/PC7 (CK on PC8)
  108. case PYB_UART_6:
  109. UARTx = USART6;
  110. GPIO_AF_UARTx = GPIO_AF8_USART6;
  111. GPIO_Port = GPIOC;
  112. GPIO_Pin = GPIO_PIN_6 | GPIO_PIN_7;
  113. __USART6_CLK_ENABLE();
  114. break;
  115. default:
  116. return false;
  117. }
  118. // init GPIO
  119. GPIO_InitTypeDef GPIO_InitStructure;
  120. GPIO_InitStructure.Pin = GPIO_Pin;
  121. GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
  122. GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
  123. GPIO_InitStructure.Pull = GPIO_PULLUP;
  124. GPIO_InitStructure.Alternate = GPIO_AF_UARTx;
  125. HAL_GPIO_Init(GPIO_Port, &GPIO_InitStructure);
  126. // init UARTx
  127. uart_obj->uart.Instance = UARTx;
  128. HAL_UART_Init(&uart_obj->uart);
  129. uart_obj->is_enabled = true;
  130. #endif
  131. return true;
  132. }
  133. bool uart_init(pyb_uart_obj_t *uart_obj, uint32_t baudrate) {
  134. #if 0
  135. UART_HandleTypeDef *uh = &uart_obj->uart;
  136. memset(uh, 0, sizeof(*uh));
  137. uh->Init.BaudRate = baudrate;
  138. uh->Init.WordLength = UART_WORDLENGTH_8B;
  139. uh->Init.StopBits = UART_STOPBITS_1;
  140. uh->Init.Parity = UART_PARITY_NONE;
  141. uh->Init.Mode = UART_MODE_TX_RX;
  142. uh->Init.HwFlowCtl = UART_HWCONTROL_NONE;
  143. uh->Init.OverSampling = UART_OVERSAMPLING_16;
  144. #endif
  145. return uart_init2(uart_obj);
  146. }
  147. mp_uint_t uart_rx_any(pyb_uart_obj_t *uart_obj) {
  148. #if 0
  149. return __HAL_UART_GET_FLAG(&uart_obj->uart, UART_FLAG_RXNE);
  150. #else
  151. return 0;
  152. #endif
  153. }
  154. int uart_rx_char(pyb_uart_obj_t *uart_obj) {
  155. uint8_t ch;
  156. #if 0
  157. if (HAL_UART_Receive(&uart_obj->uart, &ch, 1, 0) != HAL_OK) {
  158. ch = 0;
  159. }
  160. #else
  161. ch = 'A';
  162. #endif
  163. return ch;
  164. }
  165. void uart_tx_char(pyb_uart_obj_t *uart_obj, int c) {
  166. #if 0
  167. uint8_t ch = c;
  168. HAL_UART_Transmit(&uart_obj->uart, &ch, 1, 100000);
  169. #endif
  170. }
  171. void uart_tx_str(pyb_uart_obj_t *uart_obj, const char *str) {
  172. #if 0
  173. HAL_UART_Transmit(&uart_obj->uart, (uint8_t*)str, strlen(str), 100000);
  174. #endif
  175. }
  176. void uart_tx_strn(pyb_uart_obj_t *uart_obj, const char *str, uint len) {
  177. #if 0
  178. HAL_UART_Transmit(&uart_obj->uart, (uint8_t*)str, len, 100000);
  179. #endif
  180. }
  181. void uart_tx_strn_cooked(pyb_uart_obj_t *uart_obj, const char *str, uint len) {
  182. for (const char *top = str + len; str < top; str++) {
  183. if (*str == '\n') {
  184. uart_tx_char(uart_obj, '\r');
  185. }
  186. uart_tx_char(uart_obj, *str);
  187. }
  188. }
  189. /******************************************************************************/
  190. /* MicroPython bindings */
  191. STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  192. pyb_uart_obj_t *self = self_in;
  193. if (!self->is_enabled) {
  194. mp_printf(print, "UART(%lu)", self->uart_id);
  195. } else {
  196. #if 0
  197. mp_printf(print, "UART(%lu, baudrate=%u, bits=%u, stop=%u",
  198. self->uart_id, self->uart.Init.BaudRate,
  199. self->uart.Init.WordLength == UART_WORDLENGTH_8B ? 8 : 9,
  200. self->uart.Init.StopBits == UART_STOPBITS_1 ? 1 : 2);
  201. if (self->uart.Init.Parity == UART_PARITY_NONE) {
  202. mp_print_str(print, ", parity=None)");
  203. } else {
  204. mp_printf(print, ", parity=%u)", self->uart.Init.Parity == UART_PARITY_EVEN ? 0 : 1);
  205. }
  206. #endif
  207. }
  208. }
  209. /// \method init(baudrate, *, bits=8, stop=1, parity=None)
  210. ///
  211. /// Initialise the SPI bus with the given parameters:
  212. ///
  213. /// - `baudrate` is the clock rate.
  214. /// - `bits` is the number of bits per byte, 8 or 9.
  215. /// - `stop` is the number of stop bits, 1 or 2.
  216. /// - `parity` is the parity, `None`, 0 (even) or 1 (odd).
  217. STATIC const mp_arg_t pyb_uart_init_args[] = {
  218. { MP_QSTR_baudrate, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 9600} },
  219. { MP_QSTR_bits, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} },
  220. { MP_QSTR_stop, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} },
  221. { MP_QSTR_parity, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
  222. };
  223. #define PYB_UART_INIT_NUM_ARGS MP_ARRAY_SIZE(pyb_uart_init_args)
  224. STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
  225. // parse args
  226. mp_arg_val_t vals[PYB_UART_INIT_NUM_ARGS];
  227. mp_arg_parse_all(n_args, args, kw_args, PYB_UART_INIT_NUM_ARGS, pyb_uart_init_args, vals);
  228. #if 0
  229. // set the UART configuration values
  230. memset(&self->uart, 0, sizeof(self->uart));
  231. UART_InitTypeDef *init = &self->uart.Init;
  232. init->BaudRate = vals[0].u_int;
  233. init->WordLength = vals[1].u_int == 8 ? UART_WORDLENGTH_8B : UART_WORDLENGTH_9B;
  234. switch (vals[2].u_int) {
  235. case 1: init->StopBits = UART_STOPBITS_1; break;
  236. default: init->StopBits = UART_STOPBITS_2; break;
  237. }
  238. if (vals[3].u_obj == mp_const_none) {
  239. init->Parity = UART_PARITY_NONE;
  240. } else {
  241. mp_int_t parity = mp_obj_get_int(vals[3].u_obj);
  242. init->Parity = (parity & 1) ? UART_PARITY_ODD : UART_PARITY_EVEN;
  243. }
  244. init->Mode = UART_MODE_TX_RX;
  245. init->HwFlowCtl = UART_HWCONTROL_NONE;
  246. init->OverSampling = UART_OVERSAMPLING_16;
  247. // init UART (if it fails, it's because the port doesn't exist)
  248. if (!uart_init2(self)) {
  249. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART port %d does not exist", self->uart_id));
  250. }
  251. #endif
  252. return mp_const_none;
  253. }
  254. /// \classmethod \constructor(bus, ...)
  255. ///
  256. /// Construct a UART object on the given bus. `bus` can be 1-6, or 'XA', 'XB', 'YA', or 'YB'.
  257. /// With no additional parameters, the UART object is created but not
  258. /// initialised (it has the settings from the last initialisation of
  259. /// the bus, if any). If extra arguments are given, the bus is initialised.
  260. /// See `init` for parameters of initialisation.
  261. ///
  262. /// The physical pins of the UART busses are:
  263. ///
  264. /// - `UART(4)` is on `XA`: `(TX, RX) = (X1, X2) = (PA0, PA1)`
  265. /// - `UART(1)` is on `XB`: `(TX, RX) = (X9, X10) = (PB6, PB7)`
  266. /// - `UART(6)` is on `YA`: `(TX, RX) = (Y1, Y2) = (PC6, PC7)`
  267. /// - `UART(3)` is on `YB`: `(TX, RX) = (Y9, Y10) = (PB10, PB11)`
  268. /// - `UART(2)` is on: `(TX, RX) = (X3, X4) = (PA2, PA3)`
  269. STATIC mp_obj_t pyb_uart_make_new(const mp_obj_type_t *type, uint n_args, uint n_kw, const mp_obj_t *args) {
  270. // check arguments
  271. mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
  272. // create object
  273. pyb_uart_obj_t *o = m_new_obj(pyb_uart_obj_t);
  274. o->base.type = &pyb_uart_type;
  275. // work out port
  276. o->uart_id = 0;
  277. #if 0
  278. if (MP_OBJ_IS_STR(args[0])) {
  279. const char *port = mp_obj_str_get_str(args[0]);
  280. if (0) {
  281. #if defined(PYBV10)
  282. } else if (strcmp(port, "XA") == 0) {
  283. o->uart_id = PYB_UART_XA;
  284. } else if (strcmp(port, "XB") == 0) {
  285. o->uart_id = PYB_UART_XB;
  286. } else if (strcmp(port, "YA") == 0) {
  287. o->uart_id = PYB_UART_YA;
  288. } else if (strcmp(port, "YB") == 0) {
  289. o->uart_id = PYB_UART_YB;
  290. #endif
  291. } else {
  292. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART port %s does not exist", port));
  293. }
  294. } else {
  295. o->uart_id = mp_obj_get_int(args[0]);
  296. }
  297. #endif
  298. if (n_args > 1 || n_kw > 0) {
  299. // start the peripheral
  300. mp_map_t kw_args;
  301. mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
  302. pyb_uart_init_helper(o, n_args - 1, args + 1, &kw_args);
  303. }
  304. return o;
  305. }
  306. STATIC mp_obj_t pyb_uart_init(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
  307. return pyb_uart_init_helper(args[0], n_args - 1, args + 1, kw_args);
  308. }
  309. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_init_obj, 1, pyb_uart_init);
  310. /// \method deinit()
  311. /// Turn off the UART bus.
  312. STATIC mp_obj_t pyb_uart_deinit(mp_obj_t self_in) {
  313. //pyb_uart_obj_t *self = self_in;
  314. // TODO
  315. return mp_const_none;
  316. }
  317. STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_deinit_obj, pyb_uart_deinit);
  318. /// \method any()
  319. /// Return `True` if any characters waiting, else `False`.
  320. STATIC mp_obj_t pyb_uart_any(mp_obj_t self_in) {
  321. pyb_uart_obj_t *self = self_in;
  322. if (uart_rx_any(self)) {
  323. return mp_const_true;
  324. } else {
  325. return mp_const_false;
  326. }
  327. }
  328. STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_any_obj, pyb_uart_any);
  329. /// \method send(send, *, timeout=5000)
  330. /// Send data on the bus:
  331. ///
  332. /// - `send` is the data to send (an integer to send, or a buffer object).
  333. /// - `timeout` is the timeout in milliseconds to wait for the send.
  334. ///
  335. /// Return value: `None`.
  336. STATIC const mp_arg_t pyb_uart_send_args[] = {
  337. { MP_QSTR_send, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
  338. { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
  339. };
  340. #define PYB_UART_SEND_NUM_ARGS MP_ARRAY_SIZE(pyb_uart_send_args)
  341. STATIC mp_obj_t pyb_uart_send(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
  342. // TODO assumes transmission size is 8-bits wide
  343. pyb_uart_obj_t *self = args[0];
  344. // parse args
  345. mp_arg_val_t vals[PYB_UART_SEND_NUM_ARGS];
  346. mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_UART_SEND_NUM_ARGS, pyb_uart_send_args, vals);
  347. #if 0
  348. // get the buffer to send from
  349. mp_buffer_info_t bufinfo;
  350. uint8_t data[1];
  351. pyb_buf_get_for_send(vals[0].u_obj, &bufinfo, data);
  352. // send the data
  353. HAL_StatusTypeDef status = HAL_UART_Transmit(&self->uart, bufinfo.buf, bufinfo.len, vals[1].u_int);
  354. if (status != HAL_OK) {
  355. // TODO really need a HardwareError object, or something
  356. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_Exception, "HAL_UART_Transmit failed with code %d", status));
  357. }
  358. #else
  359. (void)self;
  360. #endif
  361. return mp_const_none;
  362. }
  363. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_send_obj, 1, pyb_uart_send);
  364. /// \method recv(recv, *, timeout=5000)
  365. ///
  366. /// Receive data on the bus:
  367. ///
  368. /// - `recv` can be an integer, which is the number of bytes to receive,
  369. /// or a mutable buffer, which will be filled with received bytes.
  370. /// - `timeout` is the timeout in milliseconds to wait for the receive.
  371. ///
  372. /// Return value: if `recv` is an integer then a new buffer of the bytes received,
  373. /// otherwise the same buffer that was passed in to `recv`.
  374. #if 0
  375. STATIC const mp_arg_t pyb_uart_recv_args[] = {
  376. { MP_QSTR_recv, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
  377. { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
  378. };
  379. #define PYB_UART_RECV_NUM_ARGS MP_ARRAY_SIZE(pyb_uart_recv_args)
  380. #endif
  381. STATIC mp_obj_t pyb_uart_recv(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
  382. // TODO assumes transmission size is 8-bits wide
  383. pyb_uart_obj_t *self = args[0];
  384. #if 0
  385. // parse args
  386. mp_arg_val_t vals[PYB_UART_RECV_NUM_ARGS];
  387. mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_UART_RECV_NUM_ARGS, pyb_uart_recv_args, vals);
  388. // get the buffer to receive into
  389. mp_buffer_info_t bufinfo;
  390. mp_obj_t o_ret = pyb_buf_get_for_recv(vals[0].u_obj, &bufinfo);
  391. // receive the data
  392. HAL_StatusTypeDef status = HAL_UART_Receive(&self->uart, bufinfo.buf, bufinfo.len, vals[1].u_int);
  393. if (status != HAL_OK) {
  394. // TODO really need a HardwareError object, or something
  395. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_Exception, "HAL_UART_Receive failed with code %d", status));
  396. }
  397. // return the received data
  398. if (o_ret == MP_OBJ_NULL) {
  399. return vals[0].u_obj;
  400. } else {
  401. return mp_obj_str_builder_end(o_ret);
  402. }
  403. #else
  404. (void)self;
  405. return mp_const_none;
  406. #endif
  407. }
  408. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_recv_obj, 1, pyb_uart_recv);
  409. STATIC const mp_rom_map_elem_t pyb_uart_locals_dict_table[] = {
  410. // instance methods
  411. { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_uart_init_obj) },
  412. { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_uart_deinit_obj) },
  413. { MP_ROM_QSTR(MP_QSTR_any), MP_ROM_PTR(&pyb_uart_any_obj) },
  414. { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&pyb_uart_send_obj) },
  415. { MP_ROM_QSTR(MP_QSTR_recv), MP_ROM_PTR(&pyb_uart_recv_obj) },
  416. };
  417. STATIC MP_DEFINE_CONST_DICT(pyb_uart_locals_dict, pyb_uart_locals_dict_table);
  418. const mp_obj_type_t pyb_uart_type = {
  419. { &mp_type_type },
  420. .name = MP_QSTR_UART,
  421. .print = pyb_uart_print,
  422. .make_new = pyb_uart_make_new,
  423. .locals_dict = (mp_obj_t)&pyb_uart_locals_dict,
  424. };