Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary data with pyserial(python serial port)

serial.write() method in pyserial seems to only send string data. I have arrays like [0xc0,0x04,0x00] and want to be able to send/receive them via the serial port? Are there any separate methods for raw I/O?

I think I might need to change the arrays to ['\xc0','\x04','\x00'], still, null character might pose a problem.

like image 328
Atilla Filiz Avatar asked Jan 23 '09 14:01

Atilla Filiz


People also ask

Is pySerial the same as serial?

pySerial includes a small console based terminal program called serial. tools. miniterm.

What is timeout in Python serial?

timeout = x : set timeout to x seconds (float allowed) returns immediately when the requested number of bytes are available, otherwise wait until the timeout expires and return all bytes that were received until then.

How do you exit a serial in Python?

You can use the with statement. The with statement will automatically close ser and text_file when execution leaves the with statement. This can be an exception in your case.


2 Answers

An alternative method, without using the array module:

def a2s(arr):
    """ Array of integer byte values --> binary string
    """
    return ''.join(chr(b) for b in arr)
like image 54
Eli Bendersky Avatar answered Sep 21 '22 11:09

Eli Bendersky


You need to convert your data to a string

"\xc0\x04\x00"

Null characters are not a problem in Python -- strings are not null-terminated the zero byte behaves just like another byte "\x00".

One way to do this:

>>> import array
>>> array.array('B', [0xc0, 0x04, 0x00]).tostring()
'\xc0\x04\x00'
like image 37
dF. Avatar answered Sep 19 '22 11:09

dF.