小编Kev*_*der的帖子

使用select()进行非阻塞串行

我正在开发一个项目,我需要从串口读取和写入数据,这需要非阻塞,原因我不会介入.select()函数看起来像我想要使用的,但我正在努力获得一个有效的实现.

在open_port()中,我定义了端口的设置,并且它是非阻塞的.在otherselect()中,我将描述符分配给open_port()并尝试读取.我还在函数结束时进行了1秒的睡眠调用,以避免硬件读取速度过快.

在运行时,我会在发送消息之前每秒打印一条消息,表示"没有数据可用",并且在我发送消息后将其打印出来,但它通常是带有二进制字符的碎片.例如,当发送单词"buffer"时,它将打印"ffer",后跟二进制字符.

我几乎没有使用termios或select的经验,所以任何建议都将不胜感激.

#include <iostream>
#include "stdio.h"
#include "termios.h"
#include "errno.h"
#include "fcntl.h"
#include "string.h"
#include "time.h"
#include "sys/select.h"

using namespace std;

int open_port(){
struct termios oldtio,newtio;
int serial_fd;
if ((serial_fd = open("/dev/ttyS0", O_RDWR | O_EXCL | O_NDELAY)) == -1) {
    cout << "unable to open" << endl;
    return -1;
}
if (tcgetattr(serial_fd, &oldtio) == -1) {
    cout << "tcgetattr failed" << endl;
    return -1;
}
cfmakeraw(&newtio); // Clean all settings
newtio.c_cflag = (newtio.c_cflag & ~CSIZE) | CS8 | …
Run Code Online (Sandbox Code Playgroud)

c++ linux select serial-port

9
推荐指数
1
解决办法
6083
查看次数

标签 统计

c++ ×1

linux ×1

select ×1

serial-port ×1