uart.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. * Copyright (c) 2015 Glenn Ruben Bakke
  8. * Copyright (c) 2018 Ayke van Laethem
  9. *
  10. * Permission is hereby granted, free of charge, to any person obtaining a copy
  11. * of this software and associated documentation files (the "Software"), to deal
  12. * in the Software without restriction, including without limitation the rights
  13. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. * copies of the Software, and to permit persons to whom the Software is
  15. * furnished to do so, subject to the following conditions:
  16. *
  17. * The above copyright notice and this permission notice shall be included in
  18. * all copies or substantial portions of the Software.
  19. *
  20. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. * THE SOFTWARE.
  27. */
  28. #include <stdbool.h>
  29. #include <string.h>
  30. #include <stdarg.h>
  31. #include "py/nlr.h"
  32. #include "py/runtime.h"
  33. #include "py/stream.h"
  34. #include "py/mperrno.h"
  35. #include "py/mphal.h"
  36. #include "pin.h"
  37. #include "genhdr/pins.h"
  38. #include "uart.h"
  39. #include "mpconfigboard.h"
  40. #include "nrf.h"
  41. #include "mphalport.h"
  42. #include "nrfx_uart.h"
  43. #if MICROPY_PY_MACHINE_UART
  44. typedef struct _machine_hard_uart_obj_t {
  45. mp_obj_base_t base;
  46. const nrfx_uart_t * p_uart; // Driver instance
  47. byte char_width; // 0 for 7,8 bit chars, 1 for 9 bit chars
  48. } machine_hard_uart_obj_t;
  49. static const nrfx_uart_t instance0 = NRFX_UART_INSTANCE(0);
  50. STATIC const machine_hard_uart_obj_t machine_hard_uart_obj[] = {
  51. {{&machine_hard_uart_type}, .p_uart = &instance0},
  52. };
  53. void uart_init0(void) {
  54. }
  55. STATIC int uart_find(mp_obj_t id) {
  56. // given an integer id
  57. int uart_id = mp_obj_get_int(id);
  58. if (uart_id >= 0 && uart_id < MP_ARRAY_SIZE(machine_hard_uart_obj)) {
  59. return uart_id;
  60. }
  61. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  62. "UART(%d) does not exist", uart_id));
  63. }
  64. void uart_irq_handler(mp_uint_t uart_id) {
  65. }
  66. bool uart_rx_any(const machine_hard_uart_obj_t *uart_obj) {
  67. // TODO: uart will block for now.
  68. return true;
  69. }
  70. int uart_rx_char(const machine_hard_uart_obj_t * self) {
  71. uint8_t ch;
  72. nrfx_uart_rx(self->p_uart, &ch, 1);
  73. return (int)ch;
  74. }
  75. STATIC nrfx_err_t uart_tx_char(const machine_hard_uart_obj_t * self, int c) {
  76. while (nrfx_uart_tx_in_progress(self->p_uart)) {
  77. ;
  78. }
  79. return nrfx_uart_tx(self->p_uart, (uint8_t *)&c, 1);
  80. }
  81. void uart_tx_strn(const machine_hard_uart_obj_t *uart_obj, const char *str, uint len) {
  82. for (const char *top = str + len; str < top; str++) {
  83. uart_tx_char(uart_obj, *str);
  84. }
  85. }
  86. void uart_tx_strn_cooked(const machine_hard_uart_obj_t *uart_obj, const char *str, uint len) {
  87. for (const char *top = str + len; str < top; str++) {
  88. if (*str == '\n') {
  89. uart_tx_char(uart_obj, '\r');
  90. }
  91. uart_tx_char(uart_obj, *str);
  92. }
  93. }
  94. /******************************************************************************/
  95. /* MicroPython bindings */
  96. STATIC void machine_hard_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  97. }
  98. /// \method init(baudrate, bits=8, parity=None, stop=1, *, timeout=1000, timeout_char=0, read_buf_len=64)
  99. ///
  100. /// Initialise the UART bus with the given parameters:
  101. /// - `id`is bus id.
  102. /// - `baudrate` is the clock rate.
  103. /// - `bits` is the number of bits per byte, 7, 8 or 9.
  104. /// - `parity` is the parity, `None`, 0 (even) or 1 (odd).
  105. /// - `stop` is the number of stop bits, 1 or 2.
  106. /// - `timeout` is the timeout in milliseconds to wait for the first character.
  107. /// - `timeout_char` is the timeout in milliseconds to wait between characters.
  108. /// - `read_buf_len` is the character length of the read buffer (0 to disable).
  109. STATIC mp_obj_t machine_hard_uart_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
  110. enum { ARG_id, ARG_baudrate, ARG_bits, ARG_parity, ARG_stop, ARG_flow, ARG_timeout, ARG_timeout_char, ARG_read_buf_len };
  111. static const mp_arg_t allowed_args[] = {
  112. { MP_QSTR_id, MP_ARG_REQUIRED | MP_ARG_OBJ },
  113. { MP_QSTR_baudrate, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 9600} },
  114. { MP_QSTR_bits, MP_ARG_INT, {.u_int = 8} },
  115. { MP_QSTR_parity, MP_ARG_OBJ, {.u_obj = mp_const_none} },
  116. { MP_QSTR_stop, MP_ARG_INT, {.u_int = 1} },
  117. { MP_QSTR_flow, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
  118. { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} },
  119. { MP_QSTR_timeout_char, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
  120. { MP_QSTR_read_buf_len, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 64} },
  121. };
  122. // parse args
  123. mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
  124. mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
  125. // get static peripheral object
  126. int uart_id = uart_find(args[ARG_id].u_obj);
  127. const machine_hard_uart_obj_t * self = &machine_hard_uart_obj[uart_id];
  128. nrfx_uart_config_t config;
  129. // flow control
  130. config.hwfc = args[ARG_flow].u_int;
  131. #if MICROPY_HW_UART1_HWFC
  132. config.hwfc = NRF_UART_HWFC_ENABLED;
  133. #else
  134. config.hwfc = NRF_UART_HWFC_DISABLED;
  135. #endif
  136. config.parity = NRF_UART_PARITY_EXCLUDED;
  137. #if (BLUETOOTH_SD == 100)
  138. config.interrupt_priority = 3;
  139. #else
  140. config.interrupt_priority = 6;
  141. #endif
  142. switch (args[ARG_baudrate].u_int) {
  143. case 1200:
  144. config.baudrate = NRF_UART_BAUDRATE_1200;
  145. break;
  146. case 2400:
  147. config.baudrate = NRF_UART_BAUDRATE_2400;
  148. break;
  149. case 4800:
  150. config.baudrate = NRF_UART_BAUDRATE_4800;
  151. break;
  152. case 9600:
  153. config.baudrate = NRF_UART_BAUDRATE_9600;
  154. break;
  155. case 14400:
  156. config.baudrate = NRF_UART_BAUDRATE_14400;
  157. break;
  158. case 19200:
  159. config.baudrate = NRF_UART_BAUDRATE_19200;
  160. break;
  161. case 28800:
  162. config.baudrate = NRF_UART_BAUDRATE_28800;
  163. break;
  164. case 38400:
  165. config.baudrate = NRF_UART_BAUDRATE_38400;
  166. break;
  167. case 57600:
  168. config.baudrate = NRF_UART_BAUDRATE_57600;
  169. break;
  170. case 76800:
  171. config.baudrate = NRF_UART_BAUDRATE_76800;
  172. break;
  173. case 115200:
  174. config.baudrate = NRF_UART_BAUDRATE_115200;
  175. break;
  176. case 230400:
  177. config.baudrate = NRF_UART_BAUDRATE_230400;
  178. break;
  179. case 250000:
  180. config.baudrate = NRF_UART_BAUDRATE_250000;
  181. break;
  182. case 1000000:
  183. config.baudrate = NRF_UART_BAUDRATE_1000000;
  184. break;
  185. default:
  186. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  187. "UART baudrate not supported, %u", args[ARG_baudrate].u_int));
  188. break;
  189. }
  190. config.pseltxd = MICROPY_HW_UART1_TX;
  191. config.pselrxd = MICROPY_HW_UART1_RX;
  192. #if MICROPY_HW_UART1_HWFC
  193. config.pselrts = MICROPY_HW_UART1_RTS;
  194. config.pselcts = MICROPY_HW_UART1_CTS;
  195. #endif
  196. // Set context to this instance of UART
  197. config.p_context = (void *)self;
  198. // Set NULL as callback function to keep it blocking
  199. nrfx_uart_init(self->p_uart, &config, NULL);
  200. nrfx_uart_rx_enable(self->p_uart);
  201. return MP_OBJ_FROM_PTR(self);
  202. }
  203. /// \method writechar(char)
  204. /// Write a single character on the bus. `char` is an integer to write.
  205. /// Return value: `None`.
  206. STATIC mp_obj_t machine_hard_uart_writechar(mp_obj_t self_in, mp_obj_t char_in) {
  207. machine_hard_uart_obj_t *self = self_in;
  208. // get the character to write (might be 9 bits)
  209. uint16_t data = mp_obj_get_int(char_in);
  210. nrfx_err_t err = NRFX_SUCCESS;
  211. for (int i = 0; i < 2; i++) {
  212. err = uart_tx_char(self, (int)(&data)[i]);
  213. }
  214. if (err != NRFX_SUCCESS) {
  215. mp_hal_raise(err);
  216. }
  217. return mp_const_none;
  218. }
  219. STATIC MP_DEFINE_CONST_FUN_OBJ_2(machine_hard_uart_writechar_obj, machine_hard_uart_writechar);
  220. /// \method readchar()
  221. /// Receive a single character on the bus.
  222. /// Return value: The character read, as an integer. Returns -1 on timeout.
  223. STATIC mp_obj_t machine_hard_uart_readchar(mp_obj_t self_in) {
  224. machine_hard_uart_obj_t *self = self_in;
  225. return MP_OBJ_NEW_SMALL_INT(uart_rx_char(self));
  226. }
  227. STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_hard_uart_readchar_obj, machine_hard_uart_readchar);
  228. // uart.sendbreak()
  229. STATIC mp_obj_t machine_hard_uart_sendbreak(mp_obj_t self_in) {
  230. return mp_const_none;
  231. }
  232. STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_hard_uart_sendbreak_obj, machine_hard_uart_sendbreak);
  233. STATIC const mp_rom_map_elem_t machine_hard_uart_locals_dict_table[] = {
  234. // instance methods
  235. /// \method read([nbytes])
  236. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  237. /// \method readline()
  238. { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
  239. /// \method readinto(buf[, nbytes])
  240. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  241. /// \method writechar(buf)
  242. { MP_ROM_QSTR(MP_QSTR_writechar), MP_ROM_PTR(&machine_hard_uart_writechar_obj) },
  243. { MP_ROM_QSTR(MP_QSTR_readchar), MP_ROM_PTR(&machine_hard_uart_readchar_obj) },
  244. { MP_ROM_QSTR(MP_QSTR_sendbreak), MP_ROM_PTR(&machine_hard_uart_sendbreak_obj) },
  245. // class constants
  246. /*
  247. { MP_ROM_QSTR(MP_QSTR_RTS), MP_ROM_INT(UART_HWCONTROL_RTS) },
  248. { MP_ROM_QSTR(MP_QSTR_CTS), MP_ROM_INT(UART_HWCONTROL_CTS) },
  249. */
  250. };
  251. STATIC MP_DEFINE_CONST_DICT(machine_hard_uart_locals_dict, machine_hard_uart_locals_dict_table);
  252. STATIC mp_uint_t machine_hard_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, int *errcode) {
  253. const machine_hard_uart_obj_t *self = self_in;
  254. byte *buf = buf_in;
  255. // check that size is a multiple of character width
  256. if (size & self->char_width) {
  257. *errcode = MP_EIO;
  258. return MP_STREAM_ERROR;
  259. }
  260. // convert byte size to char size
  261. size >>= self->char_width;
  262. // make sure we want at least 1 char
  263. if (size == 0) {
  264. return 0;
  265. }
  266. // read the data
  267. byte * orig_buf = buf;
  268. for (;;) {
  269. int data = uart_rx_char(self);
  270. *buf++ = data;
  271. if (--size == 0) {
  272. // return number of bytes read
  273. return buf - orig_buf;
  274. }
  275. }
  276. }
  277. STATIC mp_uint_t machine_hard_uart_write(mp_obj_t self_in, const void *buf_in, mp_uint_t size, int *errcode) {
  278. machine_hard_uart_obj_t *self = self_in;
  279. const byte *buf = buf_in;
  280. // check that size is a multiple of character width
  281. if (size & self->char_width) {
  282. *errcode = MP_EIO;
  283. return MP_STREAM_ERROR;
  284. }
  285. nrfx_err_t err = NRFX_SUCCESS;
  286. for (int i = 0; i < size; i++) {
  287. err = uart_tx_char(self, (int)((uint8_t *)buf)[i]);
  288. }
  289. if (err == NRFX_SUCCESS) {
  290. // return number of bytes written
  291. return size;
  292. } else {
  293. *errcode = mp_hal_status_to_errno_table[err];
  294. return MP_STREAM_ERROR;
  295. }
  296. }
  297. STATIC mp_uint_t machine_hard_uart_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) {
  298. machine_hard_uart_obj_t *self = self_in;
  299. (void)self;
  300. return MP_STREAM_ERROR;
  301. }
  302. STATIC const mp_stream_p_t uart_stream_p = {
  303. .read = machine_hard_uart_read,
  304. .write = machine_hard_uart_write,
  305. .ioctl = machine_hard_uart_ioctl,
  306. .is_text = false,
  307. };
  308. const mp_obj_type_t machine_hard_uart_type = {
  309. { &mp_type_type },
  310. .name = MP_QSTR_UART,
  311. .print = machine_hard_uart_print,
  312. .make_new = machine_hard_uart_make_new,
  313. .getiter = mp_identity_getiter,
  314. .iternext = mp_stream_unbuffered_iter,
  315. .protocol = &uart_stream_p,
  316. .locals_dict = (mp_obj_dict_t*)&machine_hard_uart_locals_dict,
  317. };
  318. #endif // MICROPY_PY_MACHINE_UART