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