djs*_*djs 4 linux serial-port pyserial
我有一个系统,我看到串行端口出现了我不期望的奇怪行为。我以前偶尔会在 USB 到串行适配器上看到这种情况,但现在我也在本机串行端口上看到它,频率要高得多。
系统设置为运行自动化测试,并且将首先执行一些任务,这些任务会导致在我没有打开端口的情况下从串行设备输出大量数据。设备也会自行重置。仅连接 tx/rx 线。没有流量控制。
这些任务完成后,测试件打开串口并立即失败,因为它得到了意外的响应。当我重现这个时,我发现如果我在终端程序中打开串行端口,我会看到几千字节的旧数据(似乎是在端口关闭时发送的)立即刷新。一旦我关闭这个程序,我就可以按预期运行测试。
什么可能导致这种情况发生?当设备关闭时,Linux 如何处理缓冲串行端口?如果我打开一个设备,让它发送输出,然后关闭它而不读取它,这会导致同样的问题吗?
即使未打开,Linux 终端驱动程序也会缓冲输入。这可能是一个有用的功能,特别是如果速度/奇偶校验/等。被适当设置。
要复制较小操作系统的行为,请在端口打开后立即从端口读取所有未决输入:
...
int fd = open ("/dev/ttyS0", O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
exit (1);
set_blocking (fd, 0); // disable reads blocked when no input ready
char buf [10000];
int n;
do {
n = read (fd, buf, sizeof buf);
} while (n > 0);
set_blocking (fd, 1); // enable read blocking (if desired)
... // now there is no pending input
void set_blocking (int fd, int should_block)
{
struct termios tty;
memset (&tty, 0, sizeof tty);
if (tcgetattr (fd, &tty) != 0)
{
error ("error %d getting term settings set_blocking", errno);
return;
}
tty.c_cc[VMIN] = should_block ? 1 : 0;
tty.c_cc[VTIME] = should_block ? 5 : 0; // 0.5 seconds read timeout
if (tcsetattr (fd, TCSANOW, &tty) != 0)
error ("error setting term %sblocking", should_block ? "" : "no");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6184 次 |
| 最近记录: |