Python Forum

Full Version: pyserial char by char io
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
pyserial is a nifty little module. I'm using it to communicate with 2 serial ports on my ARM eveluation board. It even allows me to send DSR which is essential for me.

However I want to receive from serial port character by character, not wait until a newline char is received as per .readline()
.read() also blocks waiting for a \n

How do I get each character as they arrive?
If you want each byte as it arrives (in a blocking fashion) you can use read(1).
read(1) also blocks waiting for \n.

Basically my interrupt handler outputs a single char '#' and toggles my LED. It can only output a single char because with the uart you have to wait until the buffer clears to send the next char, and blocking I/O in interrupt handlers is ... unwise.

So I see all the interrupts that have fired only when I press a key causing all sorts of line terminated I/O

Here's my receive process from the uart

def rxProcess():
    while (True):
        line = tty.read(1)
#        line = tty.read() # tty.readline() # Returns byte array which we coerce into string with str()
        print(line.decode('utf8'), end='') # end= supresses \n normally inherent in print
(May-15-2018, 08:54 AM)fcagney Wrote: [ -> ]read(1) also blocks waiting for \n.
Are you sure about that? That behavior doesn't make any sense, and isn't in the docs. I don't have hardware handy to test it but if I were you I'd double check that the thing sending the data over serial isn't doing something funny like never sending the byte unless there's also a newline following it.

You might also want to try setting parity=serial.PARITY_EVEN when you create the Serial object, like at https://pythonhosted.org/pyserial/shortintro.html
(May-15-2018, 08:54 AM)fcagney Wrote: [ -> ]read(1) also blocks waiting for \n.
read(1) blocks until one byte is in the buffer. It doesn't matter which char.

I use pyserial to read data from a radar transceiver. If there is a bug in pyserial,
I won't get usable data. Pyserial works fine with ftdi.

Maybe it's a hardware issue? Have you tried another serial port?
Maybe you try out a usb2tty from ftdi. They have also a python module,
which has a better performance and gives you the ability for bit banging.