Get current UART settings

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
microBoa
Posts: 13
Joined: Mon Apr 05, 2021 6:09 am

Get current UART settings

Post by microBoa » Thu Apr 08, 2021 1:26 am

I'm trying to create a configuration function that reads the current settings and prompts the user if they want to change it.

Is there a way for example to get only the current baudrate and not a tuple? of all the settings?

Code: Select all

>>> uart = UART(0, 115200)
Now at the REPL I type 'uart' and I get something like:

Code: Select all

UART(0, baudrate=115200, bits=8, parity=None, stop=1, rxbuf=15, timeout=10, timeout_char=10)
How do I get just the baudrate, or just the parity without having to parse the line?

EDIT: For example, in Lua I would do this:

Code: Select all

baud, databits, parity, stopbits = uart.getconfig(0)

microBoa
Posts: 13
Joined: Mon Apr 05, 2021 6:09 am

Re: Get current UART settings

Post by microBoa » Thu Apr 08, 2021 7:39 am

I still don't know if there's a more 'pythonic' way to do this, but in case anyone else wants to do it, this is what I whipped up for now.

Code: Select all

import ure
from machine import UART

def uart_cfg(device):

  cfg = ure.search('.*\((.*)\)', str(UART(device))).group(1).split(',')
  return cfg[1].split('=')[1], cfg[2].split('=')[1], cfg[3].split('=')[1], cfg[4].split('=')[1]
call it with the UART number like so:

Code: Select all

uart_cfg(0)
Collect the output like this:

Code: Select all

baud, databits, parity, stopbits = uart_cfg(0)

microBoa
Posts: 13
Joined: Mon Apr 05, 2021 6:09 am

Re: Get current UART settings

Post by microBoa » Thu Apr 29, 2021 2:54 am

Here's a one liner for my previous post in case anyone wants to retrieve UART settings in the future:

Code: Select all

_baud, _databits, _parity, _stopbits = tuple([x.split('=')[1] for x in str(UART(0))[8:-1].split(",")[:4]])
You can change the ':4' to ':7' if you want to also get the buffer/timeout settings.

JennaSys
Posts: 33
Joined: Tue Jul 15, 2014 8:29 am
Location: Southern California, US
Contact:

Re: Get current UART settings

Post by JennaSys » Tue Jul 27, 2021 1:06 am

Playing with Python, this turns the UART object into a subscriptable dictionary (works with uPy 1.16 but is subject to breaking with any update to the UART repr):

Code: Select all

dict([val.strip().split('=') for val in ('channel=' + str(uart).strip(')').split('(')[1:][0]).split(',')])
Which turns this repr:

Code: Select all

UART(0, baudrate=115200, bits=8, parity=None, stop=1, rxbuf=15, timeout=0, timeout_char=1)
into this dict:

Code: Select all

{'baudrate': '115200', 'bits': '8', 'parity': 'None', 'timeout': '0', 'timeout_char': '1', 'stop': '1', 'channel': '0', 'rxbuf': '15'}
John Sheehan

Post Reply