dfb61f01db
Support for Xtensa emitter and assembler, and upgraded F4 and F7 STM HAL This release adds support for the Xtensa architecture as a target for the native emitter, as well as Xtensa inline assembler. The int.from_bytes and int.to_bytes methods now require a second argument (the byte order) per CPython (only "little" is supported at this time). The "readall" method has been removed from all stream classes that used it; "read" with no arguments should be used instead. There is now support for importing packages from compiled .mpy files. Test coverage is increased to 96%. The generic I2C driver has improvements: configurable clock stretching timeout, "stop" argument added to readfrom/writeto methods, "nack" argument added to readinto, and write[to] now returns num of ACKs received. The framebuf module now handles 16-bit depth (generic colour format) and has hline, vline, rect, line methods. A new utimeq module is added for efficient queue ordering defined by modulo time (to be compatible with time.ticks_xxx functions). The pyboard.py script has been modified so that the target board is not reset between scripts or commands that are given on a single command line. For the stmhal port the STM Cube HAL has been upgraded: Cube F4 HAL to v1.13.1 (CMSIS 2.5.1, HAL v1.5.2) and Cube F7 HAL to v1.1.2. There is a more robust pyb.I2C implementation (DMA is now disabled by default, can be enabled via an option), and there is an implementation of machine.I2C with robust error handling and hardware acceleration on F4 MCUs. It is now recommended to use machine.I2C instead of pyb.I2C. The UART class is now more robust with better handling of errors/timeouts. There is also more accurate VBAT and VREFINT measurements for the ADC. New boards that are supported include: NUCLEO_F767ZI, STM32F769DISC and NUCLEO_L476RG. For the esp8266 port select/poll is now supported for sockets using the uselect module. There is support for native and viper emitters, as well as an inline assembler (with limited iRAM for storage of native functions, or the option to store code to flash). There is improved software I2C with a slight API change: scl/sda pins can be specified as positional only when "-1" is passed as the first argument to indicate the use of software I2C. It is recommended to use keyword arguments for scl/sda. There is very early support for over-the-air (OTA) updates using the yaota8266 project. A detailed list of changes follows. py core: - emitnative: fix native import emitter when in viper mode - remove readall() method, which is equivalent to read() w/o args - objexcept: allow clearing traceback with 'exc.__traceback__ = None' - runtime: mp_resume: handle exceptions in Python __next__() - mkrules.mk: rework find command so it works on OSX - *.mk: replace uses of 'sed' with $(SED) - parse: move function to check for const parse node to parse.[ch] - parse: make mp_parse_node_new_leaf an inline function - parse: add code to fold logical constants in or/and/not operations - factor persistent code load/save funcs into persistentcode.[ch] - factor out persistent-code reader into separate files - lexer: rewrite mp_lexer_new_from_str_len in terms of mp_reader_mem - lexer: provide generic mp_lexer_new_from_file based on mp_reader - lexer: rewrite mp_lexer_new_from_fd in terms of mp_reader - lexer: make lexer use an mp_reader as its source - objtype: implement __call__ handling for an instance w/o heap alloc - factor out common code from assemblers into asmbase.[ch] - stream: move ad-hoc ioctl constants to stream.h and rename them - compile: simplify configuration of native emitter - emit.h: remove long-obsolete declarations for cpython emitter - move arch-specific assembler macros from emitnative to asmXXX.h - asmbase: add MP_PLAT_COMMIT_EXEC option for handling exec code - asmxtensa: add low-level Xtensa assembler - integrate Xtensa assembler into native emitter - allow inline-assembler emitter to be generic - add inline Xtensa assembler - emitinline: embed entire asm struct instead of a pointer to it - emitinline: move inline-asm align and data methods to compiler - emitinline: move common code for end of final pass to compiler - asm: remove need for dummy_data when doing initial assembler passes - objint: from_bytes, to_bytes: require byteorder arg, require "little" - binary: do zero extension when storing a value larger than word size - builtinimport: support importing packages from compiled .mpy files - mpz: remove unreachable code in mpn_or_neg functions - runtime: zero out fs_user_mount array in mp_init - mpconfig.h: enable MICROPY_PY_SYS_EXIT by default - add MICROPY_KBD_EXCEPTION config option to provide mp_kbd_exception - compile: add an extra pass for Xtensa inline assembler - modbuiltins: remove unreachable code - objint: rename mp_obj_int_as_float to mp_obj_int_as_float_impl - emitglue: refactor to remove assert(0), to improve coverage - lexer: remove unreachable code in string tokeniser - lexer: remove unnecessary check for EOF in lexer's next_char func - lexer: permanently disable the mp_lexer_show_token function - parsenum: simplify and generalise decoding of digit values - mpz: fix assertion in mpz_set_from_str which checks value of base - mpprint: add assertion for, and comment about, valid base values - objint: simplify mp_int_format_size and remove unreachable code - unicode: comment-out unused function unichar_isprint - consistently update signatures of .make_new and .call methods - mkrules.mk: add MPY_CROSS_FLAGS option to pass flags to mpy-cross - builtinimport: fix bug when importing names from frozen packages extmod: - machine_i2c: make the clock stretching timeout configurable - machine_i2c: raise an error when clock stretching times out - machine_i2c: release SDA on bus error - machine_i2c: add a C-level I2C-protocol, refactoring soft I2C - machine_i2c: add argument to C funcs to control stop generation - machine_i2c: rewrite i2c.scan in terms of C-level protocol - machine_i2c: rewrite mem xfer funcs in terms of C-level protocol - machine_i2c: remove unneeded i2c_write_mem/i2c_read_mem funcs - machine_i2c: make C-level functions return -errno on I2C error - machine_i2c: add 'nack' argument to i2c.readinto - machine_i2c: make i2c.write[to] methods return num of ACKs recvd - machine_i2c: add 'stop' argument to i2c readfrom/writeto meths - machine_i2c: remove trivial function wrappers - machine_i2c: expose soft I2C obj and readfrom/writeto funcs - machine_i2c: add hook to constructor to call port-specific code - modurandom: allow to build with float disabled - modframebuf: make FrameBuffer handle 16bit depth - modframebuf: add back legacy FrameBuffer1 "class" - modframebuf: optimise fill and fill_rect methods - vfs_fat: implement POSIX behaviour of rename, allow to overwrite - moduselect: use stream helper function instead of ad-hoc code - moduselect: use configurable EVENT_POLL_HOOK instead of WFI - modlwip: add ioctl method to socket, with poll implementation - vfs_fat_file: allow file obj to respond to ioctl flush request - modbtree: add method to sync the database - modbtree: rename "sync" method to "flush" for consistency - modframebuf: add hline, vline, rect and line methods - machine_spi: provide reusable software SPI class - modframebuf: make framebuf implement the buffer protocol - modframebuf: store underlying buffer object to prevent GC free - modutimeq: copy of current moduheapq with timeq support for refactoring - modutimeq: refactor into optimized class - modutimeq: make time_less_than be actually "less than", not less/eq lib: - utils/interrupt_char: use core-provided mp_kbd_exception if enabled drivers: - display/ssd1306.py: update to use FrameBuffer not FrameBuffer1 - onewire: enable pull up on data pin - onewire/ds18x20: fix negative temperature calc for DS18B20 tools: - tinytest-codegen: blacklist recently added uheapq_timeq test (qemu-arm) - pyboard.py: refactor so target is not reset between scripts/cmd - mpy-tool.py: add support for OPT_CACHE_MAP_LOOKUP_IN_BYTECODE tests: - micropython: add test for import from within viper function - use read() instead of readall() - basics: add test for logical constant folding - micropython: add test for creating traceback without allocation - micropython: move alloc-less traceback test to separate test file - extmod: improve ujson coverage - basics: improve user class coverage - basics: add test for dict.fromkeys where arg is a generator - basics: add tests for if-expressions - basics: change dict_fromkeys test so it doesn't use generators - basics: enable tests for list slice getting with 3rd arg - extmod/vfs_fat_fileio: add test for constructor of FileIO type - extmod/btree1: exercise btree.flush() - extmod/framebuf1: add basics tests for hline, vline, rect, line - update for required byteorder arg for int.from_bytes()/to_bytes() - extmod: improve moductypes test coverage - extmod: improve modframebuf test coverage - micropython: get heapalloc_traceback test running on baremetal - struct*: make skippable - basics: improve mpz test coverage - float/builtin_float_round: test round() with second arg - basics/builtin_dir: add test for dir() of a type - basics: add test for builtin locals() - basics/set_pop: improve coverage of set functions - run-tests: for REPL tests make sure the REPL is exited at the end - basics: improve test coverage for generators - import: add a test which uses ... in from-import statement - add tests to improve coverage of runtime.c - add tests to improve coverage of objarray.c - extmod: add test for utimeq module - basics/lexer: add a test for newline-escaping within a string - add a coverage test for printing the parse-tree - utimeq_stable: test for partial stability of utimeq queuing - heapalloc_inst_call: test for no alloc for simple object calls - basics: add tests for parsing of ints with base 36 - basics: add tests to improve coverage of binary.c - micropython: add test for micropython.stack_use() function - extmod: improve ubinascii.c test coverage - thread: improve modthread.c test coverage - cmdline: improve repl.c autocomplete test coverage - unix: improve runtime_utils.c test coverage - pyb/uart: update test to match recent change to UART timeout_char - run-tests: allow to skip set tests - improve warning.c test coverage - float: improve formatfloat.c test coverage using Python - unix: improve formatfloat.c test coverage using C - unix/extra_coverage: add basic tests to import frozen str and mpy - types1: split out set type test to set_types - array: allow to skip test if "array" is unavailable - unix/extra_coverage: add tests for importing frozen packages unix port: - rename define for unix moduselect to MICROPY_PY_USELECT_POSIX - Makefile: update freedos target for change of USELECT config name - enable utimeq module - main: allow to print the parse tree in coverage build - Makefile: make "coverage_test" target mirror Travis test actions - moduselect: if file object passed to .register(), return it in .poll() - Makefile: split long line for coverage target, easier to modify - enable and add basic frozen str and frozen mpy in coverage build - Makefile: allow cache-map-lookup optimisation with frozen bytecode windows port: - enable READER_POSIX to get access to lexer_new_from_file stmhal port: - dma: de-init the DMA peripheral properly before initialising - i2c: add option to I2C to enable/disable use of DMA transfers - i2c: reset the I2C peripheral if there was an error on the bus - rename mp_hal_pin_set_af to _config_alt, to simplify alt config - upgrade to STM32CubeF4 v1.13.0 - CMSIS/Device 2.5.1 - upgrade to STM32CubeF4 v1.13.0 - HAL v1.5.1 - apply STM32CubeF4 v1.13.1 patch - upgrade HAL driver to v1.5.2 - hal/i2c: reapply HAL commitea040a4
for f4 - hal/sd: reapply HAL commit1d7fb82
for f4 - hal: reapply HAL commit9db719b
for f4 - hal/rcc: reapply HAL commitc568a2b
for f4 - hal/sd: reapply HAL commit09de030
for f4 - boards: configure all F4 boards to work with new HAL - make-stmconst.py: fix regex's to work with current CMSIS - i2c: handle I2C IRQs - dma: precalculate register base and bitshift on handle init - dma: mark DMA sate as READY even if HAL_DMA_Init is skipped - can: clear FIFO flags in IRQ handler - i2c: provide custom IRQ handlers - hal: do not include <stdio.h> in HAL headers - mphalport.h: use single GPIOx->BSRR register - make-stmconst.py: add support for files with invalid utf8 bytes - update HALCOMMITS due to change to hal - make-stmconst.py: restore Python 2 compatibility - update HALCOMMITS due to change to hal - moduselect: move to extmod/ for reuse by other ports - i2c: use the HAL's I2C IRQ handler for F7 and L4 MCUs - updates to get F411 MCUs compiling with latest ST HAL - i2c: remove use of legacy I2C_NOSTRETCH_DISABLED option - add beginnings of port-specific machine.I2C implementation - i2c: add support for I2C4 hardware block on F7 MCUs - i2c: expose the pyb_i2c_obj_t struct and some relevant functions - machine_i2c: provide HW implementation of I2C peripherals for F4 - add support for flash storage on STM32F415 - add back GPIO_BSRRL and GPIO_BSRRH constants to stm module - add OpenOCD configuration for STM32L4 - add address parameters to openocd config files - adc: add "mask" selection parameter to pyb.ADCAll constructor - adc: provide more accurate measure of VBAT and VREFINT - adc: make ADCAll.read_core_temp return accurate float value - adc: add ADCAll.read_vref method, returning "3.3v" value - adc: add support for F767 MCU - adc: make channel "16" always map to the temperature sensor - sdcard: clean/invalidate cache before DMA transfers with SD card - moduos: implement POSIX behaviour of rename, allow to overwrite - adc: use constants from new HAL version - refactor UART configuration to use pin objects - uart: add support for UART7 and UART8 on F7 MCUs - uart: add check that UART id is valid for the given board - cmsis: update STM32F7 CMSIS device include files to V1.1.2 - hal: update ST32CubeF7 HAL files to V1.1.2 - port of f4 hal commitc568a2b
to updated f7 hal - port of f4 hal commit09de030
to updated f7 hal - port of f4 hal commit1d7fb82
to updated f7 hal - declare and initialise PrescTables for F7 MCUs - boards/STM32F7DISC: define LSE_STARTUP_TIMEOUT - hal: update HALCOMMITS due to change in f7 hal files - refactor to use extmod implementation of software SPI class - cmsis: add CMSIS file stm32f767xx.h, V1.1.2 - add NUCLEO_F767ZI board, with openocd config for stm32f7 - cmsis: add CMSIS file stm32f769xx.h, V1.1.2 - add STM32F769DISC board files - move PY_SYS_PLATFORM config from board to general config file - mpconfigport: add weak-module links for io, collections, random - rename mp_const_vcp_interrupt to mp_kbd_exception - usb: always use the mp_kbd_exception object for VCP interrupt - use core-provided keyboard exception object - led: properly initialise timer handle to zero before using it - mphalport.h: explicitly use HAL's GPIO constants for pull modes - usrsw: use mp_hal_pin_config function instead of HAL_GPIO_Init - led: use mp_hal_pin_config function instead of HAL_GPIO_Init - sdcard: use mp_hal_pin_config function instead of HAL_GPIO_Init - add support for STM32 Nucleo64 L476RG - uart: provide a custom function to transmit over UART - uart: increase inter-character timeout by 1ms - enable utimeq module cc3200 port: - tools/smoke.py: change readall() to read() - pybspi: remove static mode=SPI.MASTER parameter for latest HW API - mods/pybspi: remove SPI.MASTER constant, it's no longer needed - update for moduselect moved to extmod/ - re-add support for UART REPL (MICROPY_STDIO_UART setting) - enable UART REPL by default - README: (re)add information about accessing REPL on serial - make: rename "deploy" target to "deploy-ota" - add targets to erase flash, deploy firmware using cc3200tool - README: reorganize and update to the current state of affairs - modwlan: add network.WLAN.print_ver() diagnostic function esp8266 port: - enable uselect module - move websocket_helper.py from scripts to modules for frozen BC - refactor to use extmod implementation of software SPI class - mpconfigport_512k: disable framebuf module for 512k build - enable native emitter for Xtensa arch - enable inline Xtensa assembler - add "ota" target to produce firmware binary for use with yaota8266 - use core-provided keyboard exception object - add "erase" target to Makefile, to erase entire flash - when doing GC be sure to trace the memory holding native code - modesp: flash_user_start(): support configuration with yaota8266 - force relinking OTA firmware image if built after normal one - scripts/inisetup: dump FS starting sector/size on error - Makefile: produce OTA firmware as firmware-ota.bin - modesp: make check_fw() work with OTA firmware - enable utimeq module - Makefile: put firmware-ota.bin in build/, for consistency - modules/flashbdev: add RESERVED_SECS before the filesystem - modules/flashbdev: remove code to patch bootloader flash size - modules/flashbdev: remove now-unused function set_bl_flash_size - modules/flashbdev: change RESERVED_SECS to 0 zephyr port: - add .gitignore to ignore Zephyr's "outdir" directory - zephyr_getchar: update to Zephyr 1.6 unified kernel API - switch to Zephyr 1.6 unified kernel API - support raw REPL - implement soft reset feature - main: initialize sys.path and sys.argv - use core-provided keyboard exception object - uart_core: access console UART directly instead of printk() hack - enable slice subscription docs: - remove references to readall() and update stream read() docs - library/index: elaborate on u-modules - library/machine.I2C: refine definitions of I2C methods - library/pyb.Accel: add hardware note about pins used by accel - library/pyb.UART: added clarification about timeouts - library/pyb.UART: moved writechar doc to sit with other writes - esp8266/tutorial: update intro to add Getting the firmware section - library/machine.I2C: fix I2C constructor docs to match impl - esp8266/tutorial: close socket after reading page content - esp8266/general: add "Scarcity of runtime resources" section - library/esp: document esp.set_native_code_location() function - library/esp: remove para and add further warning about flash - usocket: clarify that socket timeout raises OSError exception travis: - build STM32 F7 and L4 boards under Travis CI - include persistent bytecode with floats in coverage tests examples: - hwapi: button_led: Add GPIO pin read example - hwapi: add soft_pwm example converted to uasyncio - http_client: use read() instead of readall() - hwapi: add uasyncio example of fading 2 LEDs in parallel - hwapi: add example for machine.time_pulse_us() - hwapi: add hwconfig for console tracing of LED operations - accellog.py: change 1: to /sd/, and update comment about FS - hwapi/hwconfig_console: don't alloc memory in value()
1046 lines
36 KiB
C
1046 lines
36 KiB
C
/*
|
|
* This file is part of the Micro Python project, http://micropython.org/
|
|
*
|
|
* The MIT License (MIT)
|
|
*
|
|
* Copyright (c) 2013, 2014 Damien P. George
|
|
*
|
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
* of this software and associated documentation files (the "Software"), to deal
|
|
* in the Software without restriction, including without limitation the rights
|
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
* copies of the Software, and to permit persons to whom the Software is
|
|
* furnished to do so, subject to the following conditions:
|
|
*
|
|
* The above copyright notice and this permission notice shall be included in
|
|
* all copies or substantial portions of the Software.
|
|
*
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
* THE SOFTWARE.
|
|
*/
|
|
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <stdarg.h>
|
|
|
|
#include "py/ioctl.h"
|
|
#include "py/nlr.h"
|
|
#include "py/runtime.h"
|
|
#include "py/stream.h"
|
|
#include "py/mperrno.h"
|
|
#include "py/mphal.h"
|
|
#include "uart.h"
|
|
#include "irq.h"
|
|
#include "genhdr/pins.h"
|
|
|
|
/// \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. The unit of communication
|
|
/// is a character (not to be confused with a string character) which can be 8 or 9
|
|
/// bits wide.
|
|
///
|
|
/// UART objects can be created and initialised using:
|
|
///
|
|
/// from pyb import UART
|
|
///
|
|
/// uart = UART(1, 9600) # init with given baudrate
|
|
/// uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters
|
|
///
|
|
/// Bits can be 8 or 9. Parity can be None, 0 (even) or 1 (odd). Stop can be 1 or 2.
|
|
///
|
|
/// A UART object acts like a stream object and reading and writing is done
|
|
/// using the standard stream methods:
|
|
///
|
|
/// uart.read(10) # read 10 characters, returns a bytes object
|
|
/// uart.read() # read all available characters
|
|
/// uart.readline() # read a line
|
|
/// uart.readinto(buf) # read and store into the given buffer
|
|
/// uart.write('abc') # write the 3 characters
|
|
///
|
|
/// Individual characters can be read/written using:
|
|
///
|
|
/// uart.readchar() # read 1 character and returns it as an integer
|
|
/// uart.writechar(42) # write 1 character
|
|
///
|
|
/// To check if there is anything to be read, use:
|
|
///
|
|
/// uart.any() # returns True if any characters waiting
|
|
|
|
#define CHAR_WIDTH_8BIT (0)
|
|
#define CHAR_WIDTH_9BIT (1)
|
|
|
|
struct _pyb_uart_obj_t {
|
|
mp_obj_base_t base;
|
|
UART_HandleTypeDef uart; // this is 17 words big
|
|
IRQn_Type irqn;
|
|
pyb_uart_t uart_id : 8;
|
|
bool is_enabled : 1;
|
|
byte char_width; // 0 for 7,8 bit chars, 1 for 9 bit chars
|
|
uint16_t char_mask; // 0x7f for 7 bit, 0xff for 8 bit, 0x1ff for 9 bit
|
|
uint16_t timeout; // timeout waiting for first char
|
|
uint16_t timeout_char; // timeout waiting between chars
|
|
uint16_t read_buf_len; // len in chars; buf can hold len-1 chars
|
|
volatile uint16_t read_buf_head; // indexes first empty slot
|
|
uint16_t read_buf_tail; // indexes first full slot (not full if equals head)
|
|
byte *read_buf; // byte or uint16_t, depending on char size
|
|
};
|
|
|
|
STATIC mp_obj_t pyb_uart_deinit(mp_obj_t self_in);
|
|
|
|
void uart_init0(void) {
|
|
for (int i = 0; i < MP_ARRAY_SIZE(MP_STATE_PORT(pyb_uart_obj_all)); i++) {
|
|
MP_STATE_PORT(pyb_uart_obj_all)[i] = NULL;
|
|
}
|
|
}
|
|
|
|
// unregister all interrupt sources
|
|
void uart_deinit(void) {
|
|
for (int i = 0; i < MP_ARRAY_SIZE(MP_STATE_PORT(pyb_uart_obj_all)); i++) {
|
|
pyb_uart_obj_t *uart_obj = MP_STATE_PORT(pyb_uart_obj_all)[i];
|
|
if (uart_obj != NULL) {
|
|
pyb_uart_deinit(uart_obj);
|
|
}
|
|
}
|
|
}
|
|
|
|
STATIC bool uart_exists(int uart_id) {
|
|
if (uart_id > MP_ARRAY_SIZE(MP_STATE_PORT(pyb_uart_obj_all))) {
|
|
// safeguard against pyb_uart_obj_all array being configured too small
|
|
return false;
|
|
}
|
|
switch (uart_id) {
|
|
#if defined(MICROPY_HW_UART1_TX) && defined(MICROPY_HW_UART1_RX)
|
|
case PYB_UART_1: return true;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART2_TX) && defined(MICROPY_HW_UART2_RX)
|
|
case PYB_UART_2: return true;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART3_TX) && defined(MICROPY_HW_UART3_RX)
|
|
case PYB_UART_3: return true;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART4_TX) && defined(MICROPY_HW_UART4_RX)
|
|
case PYB_UART_4: return true;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART5_TX) && defined(MICROPY_HW_UART5_RX)
|
|
case PYB_UART_5: return true;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART6_TX) && defined(MICROPY_HW_UART6_RX)
|
|
case PYB_UART_6: return true;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART7_TX) && defined(MICROPY_HW_UART7_RX)
|
|
case PYB_UART_7: return true;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART8_TX) && defined(MICROPY_HW_UART8_RX)
|
|
case PYB_UART_8: return true;
|
|
#endif
|
|
|
|
default: return false;
|
|
}
|
|
}
|
|
|
|
// assumes Init parameters have been set up correctly
|
|
STATIC bool uart_init2(pyb_uart_obj_t *uart_obj) {
|
|
USART_TypeDef *UARTx;
|
|
IRQn_Type irqn;
|
|
int uart_unit;
|
|
|
|
const pin_obj_t *pins[4] = {0};
|
|
|
|
switch (uart_obj->uart_id) {
|
|
#if defined(MICROPY_HW_UART1_TX) && defined(MICROPY_HW_UART1_RX)
|
|
case PYB_UART_1:
|
|
uart_unit = 1;
|
|
UARTx = USART1;
|
|
irqn = USART1_IRQn;
|
|
pins[0] = &MICROPY_HW_UART1_TX;
|
|
pins[1] = &MICROPY_HW_UART1_RX;
|
|
__USART1_CLK_ENABLE();
|
|
break;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART2_TX) && defined(MICROPY_HW_UART2_RX)
|
|
case PYB_UART_2:
|
|
uart_unit = 2;
|
|
UARTx = USART2;
|
|
irqn = USART2_IRQn;
|
|
pins[0] = &MICROPY_HW_UART2_TX;
|
|
pins[1] = &MICROPY_HW_UART2_RX;
|
|
#if defined(MICROPY_HW_UART2_RTS)
|
|
if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_RTS) {
|
|
pins[2] = &MICROPY_HW_UART2_RTS;
|
|
}
|
|
#endif
|
|
#if defined(MICROPY_HW_UART2_CTS)
|
|
if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS) {
|
|
pins[3] = &MICROPY_HW_UART2_CTS;
|
|
}
|
|
#endif
|
|
__USART2_CLK_ENABLE();
|
|
break;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART3_TX) && defined(MICROPY_HW_UART3_RX)
|
|
case PYB_UART_3:
|
|
uart_unit = 3;
|
|
UARTx = USART3;
|
|
irqn = USART3_IRQn;
|
|
pins[0] = &MICROPY_HW_UART3_TX;
|
|
pins[1] = &MICROPY_HW_UART3_RX;
|
|
#if defined(MICROPY_HW_UART3_RTS)
|
|
if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_RTS) {
|
|
pins[2] = &MICROPY_HW_UART3_RTS;
|
|
}
|
|
#endif
|
|
#if defined(MICROPY_HW_UART3_CTS)
|
|
if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS) {
|
|
pins[3] = &MICROPY_HW_UART3_CTS;
|
|
}
|
|
#endif
|
|
__USART3_CLK_ENABLE();
|
|
break;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART4_TX) && defined(MICROPY_HW_UART4_RX)
|
|
case PYB_UART_4:
|
|
uart_unit = 4;
|
|
UARTx = UART4;
|
|
irqn = UART4_IRQn;
|
|
pins[0] = &MICROPY_HW_UART4_TX;
|
|
pins[1] = &MICROPY_HW_UART4_RX;
|
|
__UART4_CLK_ENABLE();
|
|
break;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART5_TX) && defined(MICROPY_HW_UART5_RX)
|
|
case PYB_UART_5:
|
|
uart_unit = 5;
|
|
UARTx = UART5;
|
|
irqn = UART5_IRQn;
|
|
pins[0] = &MICROPY_HW_UART5_TX;
|
|
pins[1] = &MICROPY_HW_UART5_RX;
|
|
__UART5_CLK_ENABLE();
|
|
break;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART6_TX) && defined(MICROPY_HW_UART6_RX)
|
|
case PYB_UART_6:
|
|
uart_unit = 6;
|
|
UARTx = USART6;
|
|
irqn = USART6_IRQn;
|
|
pins[0] = &MICROPY_HW_UART6_TX;
|
|
pins[1] = &MICROPY_HW_UART6_RX;
|
|
__USART6_CLK_ENABLE();
|
|
break;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART7_TX) && defined(MICROPY_HW_UART7_RX)
|
|
case PYB_UART_7:
|
|
uart_unit = 7;
|
|
UARTx = UART7;
|
|
irqn = UART7_IRQn;
|
|
pins[0] = &MICROPY_HW_UART7_TX;
|
|
pins[1] = &MICROPY_HW_UART7_RX;
|
|
__UART7_CLK_ENABLE();
|
|
break;
|
|
#endif
|
|
|
|
#if defined(MICROPY_HW_UART8_TX) && defined(MICROPY_HW_UART8_RX)
|
|
case PYB_UART_8:
|
|
uart_unit = 8;
|
|
UARTx = UART8;
|
|
irqn = UART8_IRQn;
|
|
pins[0] = &MICROPY_HW_UART8_TX;
|
|
pins[1] = &MICROPY_HW_UART8_RX;
|
|
__UART8_CLK_ENABLE();
|
|
break;
|
|
#endif
|
|
|
|
default:
|
|
// UART does not exist or is not configured for this board
|
|
return false;
|
|
}
|
|
|
|
uint32_t mode = MP_HAL_PIN_MODE_ALT;
|
|
uint32_t pull = MP_HAL_PIN_PULL_UP;
|
|
|
|
for (uint i = 0; i < 4; i++) {
|
|
if (pins[i] != NULL) {
|
|
bool ret = mp_hal_pin_config_alt(pins[i], mode, pull, AF_FN_UART, uart_unit);
|
|
if (!ret) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
|
|
uart_obj->irqn = irqn;
|
|
uart_obj->uart.Instance = UARTx;
|
|
|
|
// init UARTx
|
|
HAL_UART_Init(&uart_obj->uart);
|
|
|
|
uart_obj->is_enabled = true;
|
|
|
|
return true;
|
|
}
|
|
|
|
/* obsolete and unused
|
|
bool uart_init(pyb_uart_obj_t *uart_obj, uint32_t baudrate) {
|
|
UART_HandleTypeDef *uh = &uart_obj->uart;
|
|
memset(uh, 0, sizeof(*uh));
|
|
uh->Init.BaudRate = baudrate;
|
|
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;
|
|
uh->Init.HwFlowCtl = UART_HWCONTROL_NONE;
|
|
uh->Init.OverSampling = UART_OVERSAMPLING_16;
|
|
return uart_init2(uart_obj);
|
|
}
|
|
*/
|
|
|
|
mp_uint_t uart_rx_any(pyb_uart_obj_t *self) {
|
|
int buffer_bytes = self->read_buf_head - self->read_buf_tail;
|
|
if (buffer_bytes < 0) {
|
|
return buffer_bytes + self->read_buf_len;
|
|
} else if (buffer_bytes > 0) {
|
|
return buffer_bytes;
|
|
} else {
|
|
return __HAL_UART_GET_FLAG(&self->uart, UART_FLAG_RXNE) != RESET;
|
|
}
|
|
}
|
|
|
|
// Waits at most timeout milliseconds for at least 1 char to become ready for
|
|
// reading (from buf or for direct reading).
|
|
// Returns true if something available, false if not.
|
|
STATIC bool uart_rx_wait(pyb_uart_obj_t *self, uint32_t timeout) {
|
|
uint32_t start = HAL_GetTick();
|
|
for (;;) {
|
|
if (self->read_buf_tail != self->read_buf_head || __HAL_UART_GET_FLAG(&self->uart, UART_FLAG_RXNE) != RESET) {
|
|
return true; // have at least 1 char ready for reading
|
|
}
|
|
if (HAL_GetTick() - start >= timeout) {
|
|
return false; // timeout
|
|
}
|
|
__WFI();
|
|
}
|
|
}
|
|
|
|
// assumes there is a character available
|
|
int uart_rx_char(pyb_uart_obj_t *self) {
|
|
if (self->read_buf_tail != self->read_buf_head) {
|
|
// buffering via IRQ
|
|
int data;
|
|
if (self->char_width == CHAR_WIDTH_9BIT) {
|
|
data = ((uint16_t*)self->read_buf)[self->read_buf_tail];
|
|
} else {
|
|
data = self->read_buf[self->read_buf_tail];
|
|
}
|
|
self->read_buf_tail = (self->read_buf_tail + 1) % self->read_buf_len;
|
|
if (__HAL_UART_GET_FLAG(&self->uart, UART_FLAG_RXNE) != RESET) {
|
|
// UART was stalled by flow ctrl: re-enable IRQ now we have room in buffer
|
|
__HAL_UART_ENABLE_IT(&self->uart, UART_IT_RXNE);
|
|
}
|
|
return data;
|
|
} else {
|
|
// no buffering
|
|
#if defined(MCU_SERIES_F7) || defined(MCU_SERIES_L4)
|
|
return self->uart.Instance->RDR & self->char_mask;
|
|
#else
|
|
return self->uart.Instance->DR & self->char_mask;
|
|
#endif
|
|
}
|
|
}
|
|
|
|
// Waits at most timeout milliseconds for TX register to become empty.
|
|
// Returns true if can write, false if can't.
|
|
STATIC bool uart_tx_wait(pyb_uart_obj_t *self, uint32_t timeout) {
|
|
uint32_t start = HAL_GetTick();
|
|
for (;;) {
|
|
if (__HAL_UART_GET_FLAG(&self->uart, UART_FLAG_TXE)) {
|
|
return true; // tx register is empty
|
|
}
|
|
if (HAL_GetTick() - start >= timeout) {
|
|
return false; // timeout
|
|
}
|
|
__WFI();
|
|
}
|
|
}
|
|
|
|
// Waits at most timeout milliseconds for UART flag to be set.
|
|
// Returns true if flag is/was set, false on timeout.
|
|
STATIC bool uart_wait_flag_set(pyb_uart_obj_t *self, uint32_t flag, uint32_t timeout) {
|
|
// Note: we don't use WFI to idle in this loop because UART tx doesn't generate
|
|
// an interrupt and the flag can be set quickly if the baudrate is large.
|
|
uint32_t start = HAL_GetTick();
|
|
for (;;) {
|
|
if (__HAL_UART_GET_FLAG(&self->uart, flag)) {
|
|
return true;
|
|
}
|
|
if (timeout == 0 || HAL_GetTick() - start >= timeout) {
|
|
return false; // timeout
|
|
}
|
|
}
|
|
}
|
|
|
|
// src - a pointer to the data to send (16-bit aligned for 9-bit chars)
|
|
// num_chars - number of characters to send (9-bit chars count for 2 bytes from src)
|
|
// *errcode - returns 0 for success, MP_Exxx on error
|
|
// returns the number of characters sent (valid even if there was an error)
|
|
STATIC size_t uart_tx_data(pyb_uart_obj_t *self, const void *src_in, size_t num_chars, int *errcode) {
|
|
if (num_chars == 0) {
|
|
*errcode = 0;
|
|
return 0;
|
|
}
|
|
|
|
uint32_t timeout;
|
|
if (self->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS) {
|
|
// CTS can hold off transmission for an arbitrarily long time. Apply
|
|
// the overall timeout rather than the character timeout.
|
|
timeout = self->timeout;
|
|
} else {
|
|
// The timeout specified here is for waiting for the TX data register to
|
|
// become empty (ie between chars), as well as for the final char to be
|
|
// completely transferred. The default value for timeout_char is long
|
|
// enough for 1 char, but we need to double it to wait for the last char
|
|
// to be transferred to the data register, and then to be transmitted.
|
|
timeout = 2 * self->timeout_char;
|
|
}
|
|
|
|
const uint8_t *src = (const uint8_t*)src_in;
|
|
size_t num_tx = 0;
|
|
USART_TypeDef *uart = self->uart.Instance;
|
|
|
|
while (num_tx < num_chars) {
|
|
if (!uart_wait_flag_set(self, UART_FLAG_TXE, timeout)) {
|
|
*errcode = MP_ETIMEDOUT;
|
|
return num_tx;
|
|
}
|
|
uint32_t data;
|
|
if (self->char_width == CHAR_WIDTH_9BIT) {
|
|
data = *((uint16_t*)src) & 0x1ff;
|
|
src += 2;
|
|
} else {
|
|
data = *src++;
|
|
}
|
|
#if defined(MCU_SERIES_F4)
|
|
uart->DR = data;
|
|
#else
|
|
uart->TDR = data;
|
|
#endif
|
|
++num_tx;
|
|
}
|
|
|
|
// wait for the UART frame to complete
|
|
if (!uart_wait_flag_set(self, UART_FLAG_TC, timeout)) {
|
|
*errcode = MP_ETIMEDOUT;
|
|
return num_tx;
|
|
}
|
|
|
|
*errcode = 0;
|
|
return num_tx;
|
|
}
|
|
|
|
STATIC void uart_tx_char(pyb_uart_obj_t *uart_obj, int c) {
|
|
uint16_t ch = c;
|
|
int errcode;
|
|
uart_tx_data(uart_obj, &ch, 1, &errcode);
|
|
}
|
|
|
|
void uart_tx_strn(pyb_uart_obj_t *uart_obj, const char *str, uint len) {
|
|
int errcode;
|
|
uart_tx_data(uart_obj, str, len, &errcode);
|
|
}
|
|
|
|
void uart_tx_strn_cooked(pyb_uart_obj_t *uart_obj, const char *str, uint len) {
|
|
for (const char *top = str + len; str < top; str++) {
|
|
if (*str == '\n') {
|
|
uart_tx_char(uart_obj, '\r');
|
|
}
|
|
uart_tx_char(uart_obj, *str);
|
|
}
|
|
}
|
|
|
|
// this IRQ handler is set up to handle RXNE interrupts only
|
|
void uart_irq_handler(mp_uint_t uart_id) {
|
|
// get the uart object
|
|
pyb_uart_obj_t *self = MP_STATE_PORT(pyb_uart_obj_all)[uart_id - 1];
|
|
|
|
if (self == NULL) {
|
|
// UART object has not been set, so we can't do anything, not
|
|
// even disable the IRQ. This should never happen.
|
|
return;
|
|
}
|
|
|
|
if (__HAL_UART_GET_FLAG(&self->uart, UART_FLAG_RXNE) != RESET) {
|
|
if (self->read_buf_len != 0) {
|
|
uint16_t next_head = (self->read_buf_head + 1) % self->read_buf_len;
|
|
if (next_head != self->read_buf_tail) {
|
|
// only read data if room in buf
|
|
#if defined(MCU_SERIES_F7) || defined(MCU_SERIES_L4)
|
|
int data = self->uart.Instance->RDR; // clears UART_FLAG_RXNE
|
|
#else
|
|
int data = self->uart.Instance->DR; // clears UART_FLAG_RXNE
|
|
#endif
|
|
data &= self->char_mask;
|
|
if (self->char_width == CHAR_WIDTH_9BIT) {
|
|
((uint16_t*)self->read_buf)[self->read_buf_head] = data;
|
|
} else {
|
|
self->read_buf[self->read_buf_head] = data;
|
|
}
|
|
self->read_buf_head = next_head;
|
|
} else { // No room: leave char in buf, disable interrupt
|
|
__HAL_UART_DISABLE_IT(&self->uart, UART_IT_RXNE);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/******************************************************************************/
|
|
/* Micro Python bindings */
|
|
|
|
STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
|
|
pyb_uart_obj_t *self = self_in;
|
|
if (!self->is_enabled) {
|
|
mp_printf(print, "UART(%u)", self->uart_id);
|
|
} else {
|
|
mp_int_t bits = (self->uart.Init.WordLength == UART_WORDLENGTH_8B ? 8 : 9);
|
|
if (self->uart.Init.Parity != UART_PARITY_NONE) {
|
|
bits -= 1;
|
|
}
|
|
mp_printf(print, "UART(%u, baudrate=%u, bits=%u, parity=",
|
|
self->uart_id, self->uart.Init.BaudRate, bits);
|
|
if (self->uart.Init.Parity == UART_PARITY_NONE) {
|
|
mp_print_str(print, "None");
|
|
} else {
|
|
mp_printf(print, "%u", self->uart.Init.Parity == UART_PARITY_EVEN ? 0 : 1);
|
|
}
|
|
if (self->uart.Init.HwFlowCtl) {
|
|
mp_printf(print, ", flow=");
|
|
if (self->uart.Init.HwFlowCtl & UART_HWCONTROL_RTS) {
|
|
mp_printf(print, "RTS%s", self->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS ? "|" : "");
|
|
}
|
|
if (self->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS) {
|
|
mp_printf(print, "CTS");
|
|
}
|
|
}
|
|
mp_printf(print, ", stop=%u, timeout=%u, timeout_char=%u, read_buf_len=%u)",
|
|
self->uart.Init.StopBits == UART_STOPBITS_1 ? 1 : 2,
|
|
self->timeout, self->timeout_char,
|
|
self->read_buf_len == 0 ? 0 : self->read_buf_len - 1); // -1 to adjust for usable length of buffer
|
|
}
|
|
}
|
|
|
|
/// \method init(baudrate, bits=8, parity=None, stop=1, *, timeout=1000, timeout_char=0, flow=0, read_buf_len=64)
|
|
///
|
|
/// Initialise the UART bus with the given parameters:
|
|
///
|
|
/// - `baudrate` is the clock rate.
|
|
/// - `bits` is the number of bits per byte, 7, 8 or 9.
|
|
/// - `parity` is the parity, `None`, 0 (even) or 1 (odd).
|
|
/// - `stop` is the number of stop bits, 1 or 2.
|
|
/// - `timeout` is the timeout in milliseconds to wait for the first character.
|
|
/// - `timeout_char` is the timeout in milliseconds to wait between characters.
|
|
/// - `flow` is RTS | CTS where RTS == 256, CTS == 512
|
|
/// - `read_buf_len` is the character length of the read buffer (0 to disable).
|
|
STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
|
|
static const mp_arg_t allowed_args[] = {
|
|
{ MP_QSTR_baudrate, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 9600} },
|
|
{ MP_QSTR_bits, MP_ARG_INT, {.u_int = 8} },
|
|
{ MP_QSTR_parity, MP_ARG_OBJ, {.u_obj = mp_const_none} },
|
|
{ MP_QSTR_stop, MP_ARG_INT, {.u_int = 1} },
|
|
{ MP_QSTR_flow, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = UART_HWCONTROL_NONE} },
|
|
{ MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} },
|
|
{ MP_QSTR_timeout_char, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
|
|
{ MP_QSTR_read_buf_len, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 64} },
|
|
};
|
|
|
|
// parse args
|
|
struct {
|
|
mp_arg_val_t baudrate, bits, parity, stop, flow, timeout, timeout_char, read_buf_len;
|
|
} args;
|
|
mp_arg_parse_all(n_args, pos_args, kw_args,
|
|
MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
|
|
|
|
// set the UART configuration values
|
|
memset(&self->uart, 0, sizeof(self->uart));
|
|
UART_InitTypeDef *init = &self->uart.Init;
|
|
|
|
// baudrate
|
|
init->BaudRate = args.baudrate.u_int;
|
|
|
|
// parity
|
|
mp_int_t bits = args.bits.u_int;
|
|
if (args.parity.u_obj == mp_const_none) {
|
|
init->Parity = UART_PARITY_NONE;
|
|
} else {
|
|
mp_int_t parity = mp_obj_get_int(args.parity.u_obj);
|
|
init->Parity = (parity & 1) ? UART_PARITY_ODD : UART_PARITY_EVEN;
|
|
bits += 1; // STs convention has bits including parity
|
|
}
|
|
|
|
// number of bits
|
|
if (bits == 8) {
|
|
init->WordLength = UART_WORDLENGTH_8B;
|
|
} else if (bits == 9) {
|
|
init->WordLength = UART_WORDLENGTH_9B;
|
|
} else {
|
|
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "unsupported combination of bits and parity"));
|
|
}
|
|
|
|
// stop bits
|
|
switch (args.stop.u_int) {
|
|
case 1: init->StopBits = UART_STOPBITS_1; break;
|
|
default: init->StopBits = UART_STOPBITS_2; break;
|
|
}
|
|
|
|
// flow control
|
|
init->HwFlowCtl = args.flow.u_int;
|
|
|
|
// extra config (not yet configurable)
|
|
init->Mode = UART_MODE_TX_RX;
|
|
init->OverSampling = UART_OVERSAMPLING_16;
|
|
|
|
// 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(%d) does not exist", self->uart_id));
|
|
}
|
|
|
|
// set timeout
|
|
self->timeout = args.timeout.u_int;
|
|
|
|
// set timeout_char
|
|
// make sure it is at least as long as a whole character (13 bits to be safe)
|
|
// minimum value is 2ms because sys-tick has a resolution of only 1ms
|
|
self->timeout_char = args.timeout_char.u_int;
|
|
uint32_t min_timeout_char = 13000 / init->BaudRate + 2;
|
|
if (self->timeout_char < min_timeout_char) {
|
|
self->timeout_char = min_timeout_char;
|
|
}
|
|
|
|
// setup the read buffer
|
|
m_del(byte, self->read_buf, self->read_buf_len << self->char_width);
|
|
if (init->WordLength == UART_WORDLENGTH_9B && init->Parity == UART_PARITY_NONE) {
|
|
self->char_mask = 0x1ff;
|
|
self->char_width = CHAR_WIDTH_9BIT;
|
|
} else {
|
|
if (init->WordLength == UART_WORDLENGTH_9B || init->Parity == UART_PARITY_NONE) {
|
|
self->char_mask = 0xff;
|
|
} else {
|
|
self->char_mask = 0x7f;
|
|
}
|
|
self->char_width = CHAR_WIDTH_8BIT;
|
|
}
|
|
self->read_buf_head = 0;
|
|
self->read_buf_tail = 0;
|
|
if (args.read_buf_len.u_int <= 0) {
|
|
// no read buffer
|
|
self->read_buf_len = 0;
|
|
self->read_buf = NULL;
|
|
HAL_NVIC_DisableIRQ(self->irqn);
|
|
__HAL_UART_DISABLE_IT(&self->uart, UART_IT_RXNE);
|
|
} else {
|
|
// read buffer using interrupts
|
|
self->read_buf_len = args.read_buf_len.u_int + 1; // +1 to adjust for usable length of buffer
|
|
self->read_buf = m_new(byte, self->read_buf_len << self->char_width);
|
|
__HAL_UART_ENABLE_IT(&self->uart, UART_IT_RXNE);
|
|
HAL_NVIC_SetPriority(self->irqn, IRQ_PRI_UART, IRQ_SUBPRI_UART);
|
|
HAL_NVIC_EnableIRQ(self->irqn);
|
|
}
|
|
|
|
// compute actual baudrate that was configured
|
|
// (this formula assumes UART_OVERSAMPLING_16)
|
|
uint32_t actual_baudrate = 0;
|
|
#if defined(MCU_SERIES_F7)
|
|
UART_ClockSourceTypeDef clocksource = UART_CLOCKSOURCE_UNDEFINED;
|
|
UART_GETCLOCKSOURCE(&self->uart, clocksource);
|
|
switch (clocksource) {
|
|
case UART_CLOCKSOURCE_PCLK1: actual_baudrate = HAL_RCC_GetPCLK1Freq(); break;
|
|
case UART_CLOCKSOURCE_PCLK2: actual_baudrate = HAL_RCC_GetPCLK2Freq(); break;
|
|
case UART_CLOCKSOURCE_HSI: actual_baudrate = HSI_VALUE; break;
|
|
case UART_CLOCKSOURCE_SYSCLK: actual_baudrate = HAL_RCC_GetSysClockFreq(); break;
|
|
case UART_CLOCKSOURCE_LSE: actual_baudrate = LSE_VALUE; break;
|
|
case UART_CLOCKSOURCE_UNDEFINED: break;
|
|
}
|
|
#else
|
|
if (self->uart.Instance == USART1
|
|
#if defined(USART6)
|
|
|| self->uart.Instance == USART6
|
|
#endif
|
|
) {
|
|
actual_baudrate = HAL_RCC_GetPCLK2Freq();
|
|
} else {
|
|
actual_baudrate = HAL_RCC_GetPCLK1Freq();
|
|
}
|
|
#endif
|
|
actual_baudrate /= self->uart.Instance->BRR;
|
|
|
|
// check we could set the baudrate within 5%
|
|
uint32_t baudrate_diff;
|
|
if (actual_baudrate > init->BaudRate) {
|
|
baudrate_diff = actual_baudrate - init->BaudRate;
|
|
} else {
|
|
baudrate_diff = init->BaudRate - actual_baudrate;
|
|
}
|
|
init->BaudRate = actual_baudrate; // remember actual baudrate for printing
|
|
if (20 * baudrate_diff > init->BaudRate) {
|
|
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "set baudrate %d is not within 5%% of desired value", actual_baudrate));
|
|
}
|
|
|
|
return mp_const_none;
|
|
}
|
|
|
|
/// \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.
|
|
///
|
|
/// The physical pins of the UART busses are:
|
|
///
|
|
/// - `UART(4)` is on `XA`: `(TX, RX) = (X1, X2) = (PA0, PA1)`
|
|
/// - `UART(1)` is on `XB`: `(TX, RX) = (X9, X10) = (PB6, PB7)`
|
|
/// - `UART(6)` is on `YA`: `(TX, RX) = (Y1, Y2) = (PC6, PC7)`
|
|
/// - `UART(3)` is on `YB`: `(TX, RX) = (Y9, Y10) = (PB10, PB11)`
|
|
/// - `UART(2)` is on: `(TX, RX) = (X3, X4) = (PA2, PA3)`
|
|
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) {
|
|
// check arguments
|
|
mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
|
|
|
|
// work out port
|
|
int uart_id = 0;
|
|
if (MP_OBJ_IS_STR(args[0])) {
|
|
const char *port = mp_obj_str_get_str(args[0]);
|
|
if (0) {
|
|
#ifdef MICROPY_HW_UART1_NAME
|
|
} else if (strcmp(port, MICROPY_HW_UART1_NAME) == 0) {
|
|
uart_id = PYB_UART_1;
|
|
#endif
|
|
#ifdef MICROPY_HW_UART2_NAME
|
|
} else if (strcmp(port, MICROPY_HW_UART2_NAME) == 0) {
|
|
uart_id = PYB_UART_2;
|
|
#endif
|
|
#ifdef MICROPY_HW_UART3_NAME
|
|
} else if (strcmp(port, MICROPY_HW_UART3_NAME) == 0) {
|
|
uart_id = PYB_UART_3;
|
|
#endif
|
|
#ifdef MICROPY_HW_UART4_NAME
|
|
} else if (strcmp(port, MICROPY_HW_UART4_NAME) == 0) {
|
|
uart_id = PYB_UART_4;
|
|
#endif
|
|
#ifdef MICROPY_HW_UART5_NAME
|
|
} else if (strcmp(port, MICROPY_HW_UART5_NAME) == 0) {
|
|
uart_id = PYB_UART_5;
|
|
#endif
|
|
#ifdef MICROPY_HW_UART6_NAME
|
|
} else if (strcmp(port, MICROPY_HW_UART6_NAME) == 0) {
|
|
uart_id = PYB_UART_6;
|
|
#endif
|
|
} else {
|
|
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%s) does not exist", port));
|
|
}
|
|
} else {
|
|
uart_id = mp_obj_get_int(args[0]);
|
|
if (!uart_exists(uart_id)) {
|
|
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%d) does not exist", uart_id));
|
|
}
|
|
}
|
|
|
|
pyb_uart_obj_t *self;
|
|
if (MP_STATE_PORT(pyb_uart_obj_all)[uart_id - 1] == NULL) {
|
|
// create new UART object
|
|
self = m_new0(pyb_uart_obj_t, 1);
|
|
self->base.type = &pyb_uart_type;
|
|
self->uart_id = uart_id;
|
|
MP_STATE_PORT(pyb_uart_obj_all)[uart_id - 1] = self;
|
|
} else {
|
|
// reference existing UART object
|
|
self = MP_STATE_PORT(pyb_uart_obj_all)[uart_id - 1];
|
|
}
|
|
|
|
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);
|
|
pyb_uart_init_helper(self, n_args - 1, args + 1, &kw_args);
|
|
}
|
|
|
|
return self;
|
|
}
|
|
|
|
STATIC mp_obj_t pyb_uart_init(mp_uint_t 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);
|
|
}
|
|
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_init_obj, 1, pyb_uart_init);
|
|
|
|
/// \method deinit()
|
|
/// Turn off the UART bus.
|
|
STATIC mp_obj_t pyb_uart_deinit(mp_obj_t self_in) {
|
|
pyb_uart_obj_t *self = self_in;
|
|
self->is_enabled = false;
|
|
UART_HandleTypeDef *uart = &self->uart;
|
|
HAL_UART_DeInit(uart);
|
|
if (uart->Instance == USART1) {
|
|
HAL_NVIC_DisableIRQ(USART1_IRQn);
|
|
__USART1_FORCE_RESET();
|
|
__USART1_RELEASE_RESET();
|
|
__USART1_CLK_DISABLE();
|
|
} else if (uart->Instance == USART2) {
|
|
HAL_NVIC_DisableIRQ(USART2_IRQn);
|
|
__USART2_FORCE_RESET();
|
|
__USART2_RELEASE_RESET();
|
|
__USART2_CLK_DISABLE();
|
|
#if defined(USART3)
|
|
} else if (uart->Instance == USART3) {
|
|
HAL_NVIC_DisableIRQ(USART3_IRQn);
|
|
__USART3_FORCE_RESET();
|
|
__USART3_RELEASE_RESET();
|
|
__USART3_CLK_DISABLE();
|
|
#endif
|
|
#if defined(UART4)
|
|
} else if (uart->Instance == UART4) {
|
|
HAL_NVIC_DisableIRQ(UART4_IRQn);
|
|
__UART4_FORCE_RESET();
|
|
__UART4_RELEASE_RESET();
|
|
__UART4_CLK_DISABLE();
|
|
#endif
|
|
#if defined(UART5)
|
|
} else if (uart->Instance == UART5) {
|
|
HAL_NVIC_DisableIRQ(UART5_IRQn);
|
|
__UART5_FORCE_RESET();
|
|
__UART5_RELEASE_RESET();
|
|
__UART5_CLK_DISABLE();
|
|
#endif
|
|
#if defined(UART6)
|
|
} else if (uart->Instance == USART6) {
|
|
HAL_NVIC_DisableIRQ(USART6_IRQn);
|
|
__USART6_FORCE_RESET();
|
|
__USART6_RELEASE_RESET();
|
|
__USART6_CLK_DISABLE();
|
|
#endif
|
|
#if defined(UART7)
|
|
} else if (uart->Instance == UART7) {
|
|
HAL_NVIC_DisableIRQ(UART7_IRQn);
|
|
__UART7_FORCE_RESET();
|
|
__UART7_RELEASE_RESET();
|
|
__UART7_CLK_DISABLE();
|
|
#endif
|
|
#if defined(UART8)
|
|
} else if (uart->Instance == UART8) {
|
|
HAL_NVIC_DisableIRQ(UART8_IRQn);
|
|
__UART8_FORCE_RESET();
|
|
__UART8_RELEASE_RESET();
|
|
__UART8_CLK_DISABLE();
|
|
#endif
|
|
}
|
|
return mp_const_none;
|
|
}
|
|
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_deinit_obj, pyb_uart_deinit);
|
|
|
|
/// \method any()
|
|
/// Return `True` if any characters waiting, else `False`.
|
|
STATIC mp_obj_t pyb_uart_any(mp_obj_t self_in) {
|
|
pyb_uart_obj_t *self = self_in;
|
|
return MP_OBJ_NEW_SMALL_INT(uart_rx_any(self));
|
|
}
|
|
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_any_obj, pyb_uart_any);
|
|
|
|
/// \method writechar(char)
|
|
/// Write a single character on the bus. `char` is an integer to write.
|
|
/// Return value: `None`.
|
|
STATIC mp_obj_t pyb_uart_writechar(mp_obj_t self_in, mp_obj_t char_in) {
|
|
pyb_uart_obj_t *self = self_in;
|
|
|
|
// get the character to write (might be 9 bits)
|
|
uint16_t data = mp_obj_get_int(char_in);
|
|
|
|
// write the character
|
|
int errcode;
|
|
if (uart_tx_wait(self, self->timeout)) {
|
|
uart_tx_data(self, &data, 1, &errcode);
|
|
} else {
|
|
errcode = MP_ETIMEDOUT;
|
|
}
|
|
|
|
if (errcode != 0) {
|
|
mp_raise_OSError(errcode);
|
|
}
|
|
|
|
return mp_const_none;
|
|
}
|
|
STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_uart_writechar_obj, pyb_uart_writechar);
|
|
|
|
/// \method readchar()
|
|
/// Receive a single character on the bus.
|
|
/// Return value: The character read, as an integer. Returns -1 on timeout.
|
|
STATIC mp_obj_t pyb_uart_readchar(mp_obj_t self_in) {
|
|
pyb_uart_obj_t *self = self_in;
|
|
if (uart_rx_wait(self, self->timeout)) {
|
|
return MP_OBJ_NEW_SMALL_INT(uart_rx_char(self));
|
|
} else {
|
|
// return -1 on timeout
|
|
return MP_OBJ_NEW_SMALL_INT(-1);
|
|
}
|
|
}
|
|
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_readchar_obj, pyb_uart_readchar);
|
|
|
|
// uart.sendbreak()
|
|
STATIC mp_obj_t pyb_uart_sendbreak(mp_obj_t self_in) {
|
|
pyb_uart_obj_t *self = self_in;
|
|
#if defined(MCU_SERIES_F7) || defined(MCU_SERIES_L4)
|
|
self->uart.Instance->RQR = USART_RQR_SBKRQ; // write-only register
|
|
#else
|
|
self->uart.Instance->CR1 |= USART_CR1_SBK;
|
|
#endif
|
|
return mp_const_none;
|
|
}
|
|
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_sendbreak_obj, pyb_uart_sendbreak);
|
|
|
|
STATIC const mp_map_elem_t pyb_uart_locals_dict_table[] = {
|
|
// instance methods
|
|
|
|
{ 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 },
|
|
|
|
/// \method read([nbytes])
|
|
{ MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&mp_stream_read_obj },
|
|
/// \method readline()
|
|
{ MP_OBJ_NEW_QSTR(MP_QSTR_readline), (mp_obj_t)&mp_stream_unbuffered_readline_obj},
|
|
/// \method readinto(buf[, nbytes])
|
|
{ MP_OBJ_NEW_QSTR(MP_QSTR_readinto), (mp_obj_t)&mp_stream_readinto_obj },
|
|
/// \method write(buf)
|
|
{ MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&mp_stream_write_obj },
|
|
|
|
{ MP_OBJ_NEW_QSTR(MP_QSTR_writechar), (mp_obj_t)&pyb_uart_writechar_obj },
|
|
{ MP_OBJ_NEW_QSTR(MP_QSTR_readchar), (mp_obj_t)&pyb_uart_readchar_obj },
|
|
{ MP_OBJ_NEW_QSTR(MP_QSTR_sendbreak), (mp_obj_t)&pyb_uart_sendbreak_obj },
|
|
|
|
// class constants
|
|
{ MP_OBJ_NEW_QSTR(MP_QSTR_RTS), MP_OBJ_NEW_SMALL_INT(UART_HWCONTROL_RTS) },
|
|
{ MP_OBJ_NEW_QSTR(MP_QSTR_CTS), MP_OBJ_NEW_SMALL_INT(UART_HWCONTROL_CTS) },
|
|
};
|
|
|
|
STATIC MP_DEFINE_CONST_DICT(pyb_uart_locals_dict, pyb_uart_locals_dict_table);
|
|
|
|
STATIC mp_uint_t pyb_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, int *errcode) {
|
|
pyb_uart_obj_t *self = self_in;
|
|
byte *buf = buf_in;
|
|
|
|
// check that size is a multiple of character width
|
|
if (size & self->char_width) {
|
|
*errcode = MP_EIO;
|
|
return MP_STREAM_ERROR;
|
|
}
|
|
|
|
// convert byte size to char size
|
|
size >>= self->char_width;
|
|
|
|
// make sure we want at least 1 char
|
|
if (size == 0) {
|
|
return 0;
|
|
}
|
|
|
|
// wait for first char to become available
|
|
if (!uart_rx_wait(self, self->timeout)) {
|
|
// return EAGAIN error to indicate non-blocking (then read() method returns None)
|
|
*errcode = MP_EAGAIN;
|
|
return MP_STREAM_ERROR;
|
|
}
|
|
|
|
// read the data
|
|
byte *orig_buf = buf;
|
|
for (;;) {
|
|
int data = uart_rx_char(self);
|
|
if (self->char_width == CHAR_WIDTH_9BIT) {
|
|
*(uint16_t*)buf = data;
|
|
buf += 2;
|
|
} else {
|
|
*buf++ = data;
|
|
}
|
|
if (--size == 0 || !uart_rx_wait(self, self->timeout_char)) {
|
|
// return number of bytes read
|
|
return buf - orig_buf;
|
|
}
|
|
}
|
|
}
|
|
|
|
STATIC mp_uint_t pyb_uart_write(mp_obj_t self_in, const void *buf_in, mp_uint_t size, int *errcode) {
|
|
pyb_uart_obj_t *self = self_in;
|
|
const byte *buf = buf_in;
|
|
|
|
// check that size is a multiple of character width
|
|
if (size & self->char_width) {
|
|
*errcode = MP_EIO;
|
|
return MP_STREAM_ERROR;
|
|
}
|
|
|
|
// wait to be able to write the first character. EAGAIN causes write to return None
|
|
if (!uart_tx_wait(self, self->timeout)) {
|
|
*errcode = MP_EAGAIN;
|
|
return MP_STREAM_ERROR;
|
|
}
|
|
|
|
// write the data
|
|
size_t num_tx = uart_tx_data(self, buf, size >> self->char_width, errcode);
|
|
|
|
if (*errcode == 0 || *errcode == MP_ETIMEDOUT) {
|
|
// return number of bytes written, even if there was a timeout
|
|
return num_tx << self->char_width;
|
|
} else {
|
|
return MP_STREAM_ERROR;
|
|
}
|
|
}
|
|
|
|
STATIC mp_uint_t pyb_uart_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) {
|
|
pyb_uart_obj_t *self = self_in;
|
|
mp_uint_t ret;
|
|
if (request == MP_STREAM_POLL) {
|
|
mp_uint_t flags = arg;
|
|
ret = 0;
|
|
if ((flags & MP_STREAM_POLL_RD) && uart_rx_any(self)) {
|
|
ret |= MP_STREAM_POLL_RD;
|
|
}
|
|
if ((flags & MP_STREAM_POLL_WR) && __HAL_UART_GET_FLAG(&self->uart, UART_FLAG_TXE)) {
|
|
ret |= MP_STREAM_POLL_WR;
|
|
}
|
|
} else {
|
|
*errcode = MP_EINVAL;
|
|
ret = MP_STREAM_ERROR;
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
STATIC const mp_stream_p_t uart_stream_p = {
|
|
.read = pyb_uart_read,
|
|
.write = pyb_uart_write,
|
|
.ioctl = pyb_uart_ioctl,
|
|
.is_text = false,
|
|
};
|
|
|
|
const mp_obj_type_t pyb_uart_type = {
|
|
{ &mp_type_type },
|
|
.name = MP_QSTR_UART,
|
|
.print = pyb_uart_print,
|
|
.make_new = pyb_uart_make_new,
|
|
.getiter = mp_identity,
|
|
.iternext = mp_stream_unbuffered_iter,
|
|
.protocol = &uart_stream_p,
|
|
.locals_dict = (mp_obj_t)&pyb_uart_locals_dict,
|
|
};
|