Using micropython to initialize a UART bus, and I'm getting an error "missing 1 requires positional arguments"

Viewed 436

I have the following code I am trying to run on an ESP-WROOM-32:

from machine import UART

def do_uart_things():
    uart = UART.init(baudrate=9600, bits=8, parity=None, stop=1, rx=34,tx=35)

do_uart_things()

I am attempting to initialize a uart bus according to the documentation: https://docs.micropython.org/en/latest/library/machine.UART.html. The documentation suggests that only baudrate, bits, parity, and stop are required, however I get the "1 additional positional arguments required" error. I can not figure out why it is giving this error.

I am also assuming that the rx and tx parameters are automatically converted to the correct type of pin, as needed by the UART class, rather than me having to manually manage it.

I have managed to get slightly similar code working:

from machine import UART

def do_uart_things():
    uart = UART(1,9600)
    uart.init(baudrate=9600, bits=8, parity=None, stop=1, rx=34,tx=35)
    #Pin numbers taken from ESP data sheet--they might not be correctly formatted

do_uart_things()

Which has me thinking the documentation is unintentionally misleading, and the leading example is not intended as an "initialize it this way OR this way," but rather requires both things be done.

Am I correct in thinking the latter code example is the correct way to use the micropython UART functionalities? I am also open to referrals to any good examples of UART and I2C usage in micropython, since I've found the documentation to be a little shy of great...

1 Answers

"UART objects can be created and initialised using:..." can be a little misleading. They meant that the object can only be created by using the constructor, however it can be initialised either with the constructor, or later, after the object has been created, but using the init method on it.

As you see, the class constructor needs a first parameter id, whereas the method init() does not. So you can use the constructor

uart = UART(1,baudrate=9600, bits=8, parity=None, stop=1, rx=34,tx=35)

but you cannot use UART.init() as this is not a constructor but a method, so it needs to operate on an instance, not a class.

Related