Serial port doesn't work properly after reboot

2019-08-19 03:07发布

问题:

My program begins like this:

#!/usr/bin/env python
import sys

from serial import Serial, EIGHTBITS, PARITY_NONE, STOPBITS_ONE

SERIAL_DEVICE = '/dev/ttyUSB0'

ser = Serial(SERIAL_DEVICE, timeout=2, baudrate=9600, bytesize=EIGHTBITS,
             parity=PARITY_NONE, stopbits=STOPBITS_ONE)

The next part of the program sends something to the device and then expects a response. When I run it after reboot, it doesn't find the response it is expecting and terminates with an error (this is correct behavior apart from the fact that it doesn't see the response it expects).

However, if I run minicom and talk to the device through minicom, it works fine. If then I close minicom and run the program, it runs fine. The minicom configuration has an empty initialization string and I always exit without reset.

Needless to say, minicom has the same settings AFAICS. It also has hardware control on, but I did try rtscts=True as an argument to Serial() and saw no difference (and even if I had an error in the arguments, this doesn't explain why after executing minicom the program works properly).

回答1:

The symptom you have is an indication that your program is not initializing the serial terminal to the proper mode that it requires.

minicom has the same settings AFAICS

Seems like you choose to guess rather than gather actual data.
Use stty -a -F /dev/ttyUSB0 before and after using minicom.
The major difference is that the termios mode is probably canonical by default (after the reboot), and minicom leaves it in non-canonical mode.

Try using stty raw -F /dev/ttyUSB0 before starting your program.