PySerial client unable to write data

2.7k views Asked by At

I'm trying to write a python program which can communicate over a serial interface using PySerial module as follows:

import serial
if __name__ == '__main__':
    port = "/dev/tnt0"
    ser = serial.Serial(port, 38400)
    print ser.name
    print ser.isOpen()
    x = ser.write('hello')
    ser.close()
    print "Done!"

But if I execute the above I get the following error:

/dev/tnt0
True
Traceback (most recent call last):
File "/home/root/nested/test.py", line 15, in <module>
x = ser.write('hello')
File "/usr/local/lib/python2.7/dist-packages/serial/serialposix.py", line 518, in write
raise SerialException('write failed: %s' % (v,))
serial.serialutil.SerialException: write failed: [Errno 22] Invalid argument

I referred to the pyserial documentation and according to that this should work without an issue. Please let me know what i'm doing wrong in this.
TIA!

2

There are 2 answers

1
Andrejs Cainikovs On BEST ANSWER

/dev/tntX are emulated port pairs, and to perform a successful read or write you need to open both ports from a pair.

Think of it as a pipe - if one end is closed, you will be not able to push the data through.

1
Lucas Azevedo On

For some reason, in order to use the module tty0tty, you need to open both /dev/tnt0 and /dev/tnt1, or any of the other pairs (e.g /dev/tnt2 and /dev/tnt3).

The code below works:

import time
import serial

def main():
     vserial0 = serial.Serial(port='/dev/tnt0', baudrate=9600, bytesize=8, parity=serial.PARITY_EVEN, stopbits=1)
     vserial1 = serial.Serial(port='/dev/tnt1', baudrate=9600, bytesize=8, parity=serial.PARITY_EVEN, stopbits=1)

     n_bytes = 0 

     while n_bytes == 0:
          vserial0.write('test')
          n_bytes = vserial1.inWaiting()
          time.sleep(0.05)

     print vserial1.read(n_bytes)

if __name__ == '__main__':
     main()