uart.c 14.9 KB
Newer Older
1
2
3
#include <stdio.h>
#include <string.h>

4
5
#include "stm32f4xx_hal.h"

6
#include "mpconfig.h"
7
#include "nlr.h"
8
9
10
#include "misc.h"
#include "qstr.h"
#include "obj.h"
11
12
#include "runtime.h"
#include "bufhelper.h"
Damien George's avatar
Damien George committed
13
#include "uart.h"
14

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/// \moduleref pyb
/// \class UART - duplex serial communication bus
///
/// UART implements the standard UART/USART duplex serial communications protocol.  At
/// the physical level it consists of 2 lines: RX and TX.
///
/// See usage model of I2C.  UART is very similar.  Main difference is
/// parameters to init the UART bus:
///
///     from pyb import UART
///
///     uart = UART(1, 9600)                         # init with given baudrate
///     uart.init(9600, bits=8, stop=1, parity=None) # init with given parameters
///
/// Bits can be 8 or 9, stop can be 1 or 2, parity can be None, 0 (even), 1 (odd).
///
/// Extra method:
///
///     uart.any()               # returns True if any characters waiting
34

Damien George's avatar
Damien George committed
35
struct _pyb_uart_obj_t {
Dave Hylands's avatar
Dave Hylands committed
36
    mp_obj_base_t base;
Damien George's avatar
Damien George committed
37
    pyb_uart_t uart_id;
Dave Hylands's avatar
Dave Hylands committed
38
    bool is_enabled;
39
    UART_HandleTypeDef uart;
Dave Hylands's avatar
Dave Hylands committed
40
};
41

Damien George's avatar
Damien George committed
42
pyb_uart_obj_t *pyb_uart_global_debug = NULL;
43

44
// assumes Init parameters have been set up correctly
Damien George's avatar
Damien George committed
45
46
bool uart_init2(pyb_uart_obj_t *uart_obj) {
    USART_TypeDef *UARTx = NULL;
47

48
    uint32_t GPIO_Pin = 0;
Damien George's avatar
Damien George committed
49
    uint8_t  GPIO_AF_UARTx = 0;
50
    GPIO_TypeDef* GPIO_Port = NULL;
51

Damien George's avatar
Damien George committed
52
53
54
55
56
    switch (uart_obj->uart_id) {
        // USART1 is on PA9/PA10 (CK on PA8), PB6/PB7
        case PYB_UART_1:
            UARTx = USART1;
            GPIO_AF_UARTx = GPIO_AF7_USART1;
57

Damien George's avatar
Damien George committed
58
#if defined (PYBV4) || defined(PYBV10)
59
60
61
            GPIO_Port = GPIOB;
            GPIO_Pin = GPIO_PIN_6 | GPIO_PIN_7;
#else
62
63
            GPIO_Port = GPIOA;
            GPIO_Pin = GPIO_PIN_9 | GPIO_PIN_10;
64
#endif
65
66
67

            __USART1_CLK_ENABLE();
            break;
68

Damien George's avatar
Damien George committed
69
70
71
72
        // USART2 is on PA2/PA3 (CK on PA4), PD5/PD6 (CK on PD7)
        case PYB_UART_2:
            UARTx = USART2;
            GPIO_AF_UARTx = GPIO_AF7_USART2;
73

Damien George's avatar
Damien George committed
74
75
            GPIO_Port = GPIOA;
            GPIO_Pin = GPIO_PIN_2 | GPIO_PIN_3;
76
77
78

            __USART2_CLK_ENABLE();
            break;
79

Damien George's avatar
Damien George committed
80
81
82
83
        // USART3 is on PB10/PB11 (CK on PB12), PC10/PC11 (CK on PC12), PD8/PD9 (CK on PD10)
        case PYB_UART_3:
            UARTx = USART3;
            GPIO_AF_UARTx = GPIO_AF7_USART3;
84

85
#if defined(PYBV3) || defined(PYBV4) | defined(PYBV10)
86
87
88
89
90
91
92
93
            GPIO_Port = GPIOB;
            GPIO_Pin = GPIO_PIN_10 | GPIO_PIN_11;
#else
            GPIO_Port = GPIOD;
            GPIO_Pin = GPIO_PIN_8 | GPIO_PIN_9;
#endif
            __USART3_CLK_ENABLE();
            break;
94

95
        // UART4 is on PA0/PA1, PC10/PC11
Damien George's avatar
Damien George committed
96
97
98
        case PYB_UART_4:
            UARTx = UART4;
            GPIO_AF_UARTx = GPIO_AF8_UART4;
99
100
101
102
103
104
105

            GPIO_Port = GPIOA;
            GPIO_Pin = GPIO_PIN_0 | GPIO_PIN_1;

            __UART4_CLK_ENABLE();
            break;

Damien George's avatar
Damien George committed
106
107
108
109
        // USART6 is on PC6/PC7 (CK on PC8)
        case PYB_UART_6:
            UARTx = USART6;
            GPIO_AF_UARTx = GPIO_AF8_USART6;
110
111
112
113
114
115

            GPIO_Port = GPIOC;
            GPIO_Pin = GPIO_PIN_6 | GPIO_PIN_7;

            __USART6_CLK_ENABLE();
            break;
116
117
118

        default:
            return false;
119
120
    }

121
    // init GPIO
122
123
124
125
126
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.Pin = GPIO_Pin;
    GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
    GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStructure.Pull = GPIO_PULLUP;
Damien George's avatar
Damien George committed
127
    GPIO_InitStructure.Alternate = GPIO_AF_UARTx;
128
129
    HAL_GPIO_Init(GPIO_Port, &GPIO_InitStructure);

Damien George's avatar
Damien George committed
130
131
132
    // init UARTx
    uart_obj->uart.Instance = UARTx;
    HAL_UART_Init(&uart_obj->uart);
133

Damien George's avatar
Damien George committed
134
    uart_obj->is_enabled = true;
135
136
137
138

    return true;
}

Damien George's avatar
Damien George committed
139
140
bool uart_init(pyb_uart_obj_t *uart_obj, uint32_t baudrate) {
    UART_HandleTypeDef *uh = &uart_obj->uart;
Dave Hylands's avatar
Dave Hylands committed
141
142
    memset(uh, 0, sizeof(*uh));
    uh->Init.BaudRate = baudrate;
143
144
145
146
    uh->Init.WordLength = UART_WORDLENGTH_8B;
    uh->Init.StopBits = UART_STOPBITS_1;
    uh->Init.Parity = UART_PARITY_NONE;
    uh->Init.Mode = UART_MODE_TX_RX;
Dave Hylands's avatar
Dave Hylands committed
147
148
    uh->Init.HwFlowCtl = UART_HWCONTROL_NONE;
    uh->Init.OverSampling = UART_OVERSAMPLING_16;
Damien George's avatar
Damien George committed
149
    return uart_init2(uart_obj);
150
}
151

Damien George's avatar
Damien George committed
152
153
154
void uart_deinit(pyb_uart_obj_t *uart_obj) {
    uart_obj->is_enabled = false;
    UART_HandleTypeDef *uart = &uart_obj->uart;
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
    HAL_UART_DeInit(uart);
    if (uart->Instance == USART1) {
        __USART1_FORCE_RESET();
        __USART1_RELEASE_RESET();
        __USART1_CLK_DISABLE();
    } else if (uart->Instance == USART2) {
        __USART2_FORCE_RESET();
        __USART2_RELEASE_RESET();
        __USART2_CLK_DISABLE();
    } else if (uart->Instance == USART3) {
        __USART3_FORCE_RESET();
        __USART3_RELEASE_RESET();
        __USART3_CLK_DISABLE();
    } else if (uart->Instance == UART4) {
        __UART4_FORCE_RESET();
        __UART4_RELEASE_RESET();
        __UART4_CLK_DISABLE();
    } else if (uart->Instance == USART6) {
        __USART6_FORCE_RESET();
        __USART6_RELEASE_RESET();
        __USART6_CLK_DISABLE();
    }
177
178
}

Damien George's avatar
Damien George committed
179
180
bool uart_rx_any(pyb_uart_obj_t *uart_obj) {
    return __HAL_UART_GET_FLAG(&uart_obj->uart, UART_FLAG_RXNE);
181
182
}

Damien George's avatar
Damien George committed
183
int uart_rx_char(pyb_uart_obj_t *uart_obj) {
184
    uint8_t ch;
Damien George's avatar
Damien George committed
185
    if (HAL_UART_Receive(&uart_obj->uart, &ch, 1, 0) != HAL_OK) {
186
187
188
189
190
        ch = 0;
    }
    return ch;
}

Damien George's avatar
Damien George committed
191
void uart_tx_char(pyb_uart_obj_t *uart_obj, int c) {
192
    uint8_t ch = c;
Damien George's avatar
Damien George committed
193
    HAL_UART_Transmit(&uart_obj->uart, &ch, 1, 100000);
194
195
}

Damien George's avatar
Damien George committed
196
197
void uart_tx_str(pyb_uart_obj_t *uart_obj, const char *str) {
    HAL_UART_Transmit(&uart_obj->uart, (uint8_t*)str, strlen(str), 100000);
198
199
}

Damien George's avatar
Damien George committed
200
201
void uart_tx_strn(pyb_uart_obj_t *uart_obj, const char *str, uint len) {
    HAL_UART_Transmit(&uart_obj->uart, (uint8_t*)str, len, 100000);
202
203
}

Damien George's avatar
Damien George committed
204
void uart_tx_strn_cooked(pyb_uart_obj_t *uart_obj, const char *str, uint len) {
205
206
    for (const char *top = str + len; str < top; str++) {
        if (*str == '\n') {
Damien George's avatar
Damien George committed
207
            uart_tx_char(uart_obj, '\r');
208
        }
Damien George's avatar
Damien George committed
209
        uart_tx_char(uart_obj, *str);
210
211
212
213
214
215
    }
}

/******************************************************************************/
/* Micro Python bindings                                                      */

Damien George's avatar
Damien George committed
216
217
STATIC void pyb_uart_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
    pyb_uart_obj_t *self = self_in;
218
    if (!self->is_enabled) {
Damien George's avatar
Damien George committed
219
        print(env, "UART(%lu)", self->uart_id);
220
    } else {
Damien George's avatar
Damien George committed
221
222
        print(env, "UART(%lu, baudrate=%u, bits=%u, stop=%u",
            self->uart_id, self->uart.Init.BaudRate,
223
224
225
226
227
228
229
230
            self->uart.Init.WordLength == UART_WORDLENGTH_8B ? 8 : 9,
            self->uart.Init.StopBits == UART_STOPBITS_1 ? 1 : 2);
        if (self->uart.Init.Parity == UART_PARITY_NONE) {
            print(env, ", parity=None)");
        } else {
            print(env, ", parity=%u)", self->uart.Init.Parity == UART_PARITY_EVEN ? 0 : 1);
        }
    }
231
232
}

233
234
235
236
237
238
239
240
/// \method init(baudrate, *, bits=8, stop=1, parity=None)
///
/// Initialise the SPI bus with the given parameters:
///
///   - `baudrate` is the clock rate.
///   - `bits` is the number of bits per byte, 8 or 9.
///   - `stop` is the number of stop bits, 1 or 2.
///   - `parity` is the parity, `None`, 0 (even) or 1 (odd).
241
242
243
244
245
STATIC const mp_arg_t pyb_uart_init_args[] = {
    { MP_QSTR_baudrate, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 9600} },
    { MP_QSTR_bits,     MP_ARG_KW_ONLY | MP_ARG_INT,  {.u_int = 8} },
    { MP_QSTR_stop,     MP_ARG_KW_ONLY | MP_ARG_INT,  {.u_int = 1} },
    { MP_QSTR_parity,   MP_ARG_KW_ONLY | MP_ARG_OBJ,  {.u_obj = mp_const_none} },
246
};
247
#define PYB_UART_INIT_NUM_ARGS ARRAY_SIZE(pyb_uart_init_args)
248

Damien George's avatar
Damien George committed
249
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) {
250
    // parse args
251
252
    mp_arg_val_t vals[PYB_UART_INIT_NUM_ARGS];
    mp_arg_parse_all(n_args, args, kw_args, PYB_UART_INIT_NUM_ARGS, pyb_uart_init_args, vals);
253

Damien George's avatar
Damien George committed
254
    // set the UART configuration values
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
    memset(&self->uart, 0, sizeof(self->uart));
    UART_InitTypeDef *init = &self->uart.Init;
    init->BaudRate = vals[0].u_int;
    init->WordLength = vals[1].u_int == 8 ? UART_WORDLENGTH_8B : UART_WORDLENGTH_9B;
    switch (vals[2].u_int) {
        case 1: init->StopBits = UART_STOPBITS_1; break;
        default: init->StopBits = UART_STOPBITS_2; break;
    }
    if (vals[3].u_obj == mp_const_none) {
        init->Parity = UART_PARITY_NONE;
    } else {
        machine_int_t parity = mp_obj_get_int(vals[3].u_obj);
        init->Parity = (parity & 1) ? UART_PARITY_ODD : UART_PARITY_EVEN;
    }
    init->Mode = UART_MODE_TX_RX;
    init->HwFlowCtl = UART_HWCONTROL_NONE;
    init->OverSampling = UART_OVERSAMPLING_16;

Damien George's avatar
Damien George committed
273
274
275
    // init UART (if it fails, it's because the port doesn't exist)
    if (!uart_init2(self)) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART port %d does not exist", self->uart_id));
276
277
    }

278
279
280
    return mp_const_none;
}

281
282
283
284
285
286
287
/// \classmethod \constructor(bus, ...)
///
/// Construct a UART object on the given bus.  `bus` can be 1-6, or 'XA', 'XB', 'YA', or 'YB'.
/// With no additional parameters, the UART object is created but not
/// initialised (it has the settings from the last initialisation of
/// the bus, if any).  If extra arguments are given, the bus is initialised.
/// See `init` for parameters of initialisation.
Damien George's avatar
Damien George committed
288
STATIC mp_obj_t pyb_uart_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
289
290
291
    // check arguments
    mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);

292
    // create object
Damien George's avatar
Damien George committed
293
294
    pyb_uart_obj_t *o = m_new_obj(pyb_uart_obj_t);
    o->base.type = &pyb_uart_type;
295

296
    // work out port
Damien George's avatar
Damien George committed
297
    o->uart_id = 0;
298
299
    if (MP_OBJ_IS_STR(args[0])) {
        const char *port = mp_obj_str_get_str(args[0]);
300
301
302
        if (0) {
#if defined(PYBV10)
        } else if (strcmp(port, "XA") == 0) {
Damien George's avatar
Damien George committed
303
            o->uart_id = PYB_UART_XA;
304
        } else if (strcmp(port, "XB") == 0) {
Damien George's avatar
Damien George committed
305
            o->uart_id = PYB_UART_XB;
306
        } else if (strcmp(port, "YA") == 0) {
Damien George's avatar
Damien George committed
307
            o->uart_id = PYB_UART_YA;
308
        } else if (strcmp(port, "YB") == 0) {
Damien George's avatar
Damien George committed
309
            o->uart_id = PYB_UART_YB;
310
#endif
311
        } else {
Damien George's avatar
Damien George committed
312
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART port %s does not exist", port));
313
        }
314
    } else {
Damien George's avatar
Damien George committed
315
        o->uart_id = mp_obj_get_int(args[0]);
316
317
    }

318
319
320
321
    if (n_args > 1 || n_kw > 0) {
        // start the peripheral
        mp_map_t kw_args;
        mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
Damien George's avatar
Damien George committed
322
        pyb_uart_init_helper(o, n_args - 1, args + 1, &kw_args);
323
324
    }

325
326
327
    return o;
}

Damien George's avatar
Damien George committed
328
329
STATIC mp_obj_t pyb_uart_init(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
    return pyb_uart_init_helper(args[0], n_args - 1, args + 1, kw_args);
330
}
Damien George's avatar
Damien George committed
331
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_init_obj, 1, pyb_uart_init);
332

333
334
/// \method deinit()
/// Turn off the UART bus.
Damien George's avatar
Damien George committed
335
336
337
STATIC mp_obj_t pyb_uart_deinit(mp_obj_t self_in) {
    pyb_uart_obj_t *self = self_in;
    uart_deinit(self);
338
339
    return mp_const_none;
}
Damien George's avatar
Damien George committed
340
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_deinit_obj, pyb_uart_deinit);
341

342
343
/// \method any()
/// Return `True` if any characters waiting, else `False`.
Damien George's avatar
Damien George committed
344
345
346
STATIC mp_obj_t pyb_uart_any(mp_obj_t self_in) {
    pyb_uart_obj_t *self = self_in;
    if (uart_rx_any(self)) {
347
348
349
350
351
        return mp_const_true;
    } else {
        return mp_const_false;
    }
}
Damien George's avatar
Damien George committed
352
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_any_obj, pyb_uart_any);
353

354
355
356
357
358
359
360
/// \method send(send, *, timeout=5000)
/// Send data on the bus:
///
///   - `send` is the data to send (an integer to send, or a buffer object).
///   - `timeout` is the timeout in milliseconds to wait for the send.
///
/// Return value: `None`.
361
362
363
STATIC const mp_arg_t pyb_uart_send_args[] = {
    { MP_QSTR_send,    MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
    { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
364
};
365
#define PYB_UART_SEND_NUM_ARGS ARRAY_SIZE(pyb_uart_send_args)
366

Damien George's avatar
Damien George committed
367
STATIC mp_obj_t pyb_uart_send(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
368
    // TODO assumes transmission size is 8-bits wide
369

Damien George's avatar
Damien George committed
370
    pyb_uart_obj_t *self = args[0];
371

372
    // parse args
373
374
    mp_arg_val_t vals[PYB_UART_SEND_NUM_ARGS];
    mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_UART_SEND_NUM_ARGS, pyb_uart_send_args, vals);
375
376
377
378
379
380
381
382
383
384
385
386

    // get the buffer to send from
    mp_buffer_info_t bufinfo;
    uint8_t data[1];
    pyb_buf_get_for_send(vals[0].u_obj, &bufinfo, data);

    // send the data
    HAL_StatusTypeDef status = HAL_UART_Transmit(&self->uart, bufinfo.buf, bufinfo.len, vals[1].u_int);

    if (status != HAL_OK) {
        // TODO really need a HardwareError object, or something
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_Exception, "HAL_UART_Transmit failed with code %d", status));
387
    }
388

389
390
    return mp_const_none;
}
Damien George's avatar
Damien George committed
391
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_send_obj, 1, pyb_uart_send);
392

393
394
395
396
397
398
399
400
401
402
/// \method recv(recv, *, timeout=5000)
///
/// Receive data on the bus:
///
///   - `recv` can be an integer, which is the number of bytes to receive,
///     or a mutable buffer, which will be filled with received bytes.
///   - `timeout` is the timeout in milliseconds to wait for the receive.
///
/// Return value: if `recv` is an integer then a new buffer of the bytes received,
/// otherwise the same buffer that was passed in to `recv`.
403
404
405
STATIC const mp_arg_t pyb_uart_recv_args[] = {
    { MP_QSTR_recv,    MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
    { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
406
};
407
#define PYB_UART_RECV_NUM_ARGS ARRAY_SIZE(pyb_uart_recv_args)
408

Damien George's avatar
Damien George committed
409
STATIC mp_obj_t pyb_uart_recv(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
410
    // TODO assumes transmission size is 8-bits wide
411

Damien George's avatar
Damien George committed
412
    pyb_uart_obj_t *self = args[0];
413

414
    // parse args
415
416
    mp_arg_val_t vals[PYB_UART_RECV_NUM_ARGS];
    mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_UART_RECV_NUM_ARGS, pyb_uart_recv_args, vals);
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436

    // get the buffer to receive into
    mp_buffer_info_t bufinfo;
    mp_obj_t o_ret = pyb_buf_get_for_recv(vals[0].u_obj, &bufinfo);

    // receive the data
    HAL_StatusTypeDef status = HAL_UART_Receive(&self->uart, bufinfo.buf, bufinfo.len, vals[1].u_int);

    if (status != HAL_OK) {
        // TODO really need a HardwareError object, or something
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_Exception, "HAL_UART_Receive failed with code %d", status));
    }

    // return the received data
    if (o_ret == MP_OBJ_NULL) {
        return vals[0].u_obj;
    } else {
        return mp_obj_str_builder_end(o_ret);
    }
}
Damien George's avatar
Damien George committed
437
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_recv_obj, 1, pyb_uart_recv);
438

Damien George's avatar
Damien George committed
439
STATIC const mp_map_elem_t pyb_uart_locals_dict_table[] = {
440
    // instance methods
Damien George's avatar
Damien George committed
441
442
443
444
445
    { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&pyb_uart_init_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&pyb_uart_deinit_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_any), (mp_obj_t)&pyb_uart_any_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_send), (mp_obj_t)&pyb_uart_send_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_recv), (mp_obj_t)&pyb_uart_recv_obj },
446
447
};

Damien George's avatar
Damien George committed
448
STATIC MP_DEFINE_CONST_DICT(pyb_uart_locals_dict, pyb_uart_locals_dict_table);
449

Damien George's avatar
Damien George committed
450
const mp_obj_type_t pyb_uart_type = {
451
    { &mp_type_type },
Damien George's avatar
Damien George committed
452
453
454
455
    .name = MP_QSTR_UART,
    .print = pyb_uart_print,
    .make_new = pyb_uart_make_new,
    .locals_dict = (mp_obj_t)&pyb_uart_locals_dict,
456
};