Page 1 of 1

newbie bytes byte-arrays and uarts

Posted: Tue Feb 08, 2022 7:12 pm
by iiLaw
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'

Re: newbie bytes byte-arrays and uarts

Posted: Tue Feb 08, 2022 10:57 pm
by fivdi
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.

Re: newbie bytes byte-arrays and uarts

Posted: Wed Feb 09, 2022 9:14 am
by iiLaw
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 :)