newbie bytes byte-arrays and uarts

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
iiLaw
Posts: 5
Joined: Sun Jan 23, 2022 10:04 am

newbie bytes byte-arrays and uarts

Post by iiLaw » Tue Feb 08, 2022 7:12 pm

Hi I'm very new to Python and wondering if there is a correct form passing data to a UART on pi Pico
I've found two different ways construct the payload via a byte-array and a sequence of bytes.
My question is do I have potential issues with either/both?
Many thanks in advance.

# byte-array
>>>modDataBA = bytearray(b'\x05\x03\x07\x00\x00\x00\x00\x0A')
>>>modDataBA.append(s0Dis)
>>>modDataBA.append(s0Dos)
>>>modDataBA: bytearray(b'\x05\x03\x07\x00\x00\x00\x00\n\x01\x01')

# byte-sequence
>>>modDataBY = b'\x05\x03\x07\x00\x00\x00\x00\x0A'+(s0Dis).to_bytes(1,'big')+(s0Dos).to_bytes(1,'big')
>>>modDataBY: <class 'bytes'> b'\x05\x03\x07\x00\x00\x00\x00\n\x01\x01'

fivdi
Posts: 16
Joined: Thu Feb 03, 2022 10:28 pm
Contact:

Re: newbie bytes byte-arrays and uarts

Post by fivdi » Tue Feb 08, 2022 10:57 pm

When UART.write(buf) is called, the buf passed can be any object that implements the buffer protocol such as bytes, bytearray, memoryview and str. See also buffer protocol.

iiLaw
Posts: 5
Joined: Sun Jan 23, 2022 10:04 am

Re: newbie bytes byte-arrays and uarts

Post by iiLaw » Wed Feb 09, 2022 9:14 am

Thanks for pointing me in that direction.

I had google around and Buffer Object & Protocol get deep very quickly.
But found this helpful https://docs.python.org/3/glossary.html ... ike-object
Though it looks like micro-python treats str differently from CPython.

When I started with micro-python I was sending AT commands which are strings
>>> atCmd = cmd + '\r\n'
>>> uart.write(atCmd)

And didn't question why it just worked so now know.
I've moved on to doing Modbus which is a binary protocol :)

Post Reply