Linux, serial port, non-buffering mode

2020-04-10 02:25发布

问题:

I am trying to organize nob-blocking read-write functionality with serial port in Linux. Here is the code I have: http://pastebin.com/RSPw7HAi It all works fine, but it is buffered. That means, that if I do input to serial via console + CR symbol, select detects new input, otherwise, if I do input via simple python script, it buffers all symbols and waits until I send it carriage return symbol. So with this input (given below) it simply buffers symbols somewhere. I have to PCs connected via USB2Serial converter

#!/usr/bin/env python3

import serial

cmd1_state = b'\x3E\x01\x00\x01'

#Selecting serial port for commands to be sent --> /dev/ttyUSB0
serial_0 = serial.Serial('/dev/ttyUSB2');
print("Using serial port ", serial_0.portstr);
serial_0.write(cmd1_state)

# closing serial port
serial_0.close()

So, can anybody tell me what to do here? Do I have to change something within port opening in my C file or it's to be done with python script? I used flush() method in later, but it also did not help. BTW, I've googled out about F_NOCACHE arg to fcntl() function. BUT! It's all about BSD and Darwin OS's, there is no such thing (F_NOACHE arg to fcntl) in Linux, as far as I could see.

UPD: Looks like I found out the solution.

 /* set input mode (non-canonical, no echo,...) */
newtio.c_lflag = 0;

newtio.c_cc[VTIME]    = 0;   /* inter-character timer unused */
newtio.c_cc[VMIN]     = 1;   /* blocking read until 1 char received */

tcflush(fd, TCIFLUSH);

Taken from : http://tldp.org/HOWTO/Serial-Programming-HOWTO/x115.html

回答1:

Looks like I found out the solution.

/* set input mode (non-canonical, no echo,...) */
newtio.c_lflag = 0;

newtio.c_cc[VTIME]    = 0;   /* inter-character timer unused */
newtio.c_cc[VMIN]     = 1;   /* blocking read until 1 char received */

tcflush(fd, TCIFLUSH);
Taken from : http://tldp.org/HOWTO/Serial-Programming-HOWTO/x115.html