Kev*_*der 9 c++ linux select serial-port
我正在开发一个项目,我需要从串口读取和写入数据,这需要非阻塞,原因我不会介入.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 | B115200; // 8 databits
newtio.c_cflag |= (CLOCAL | CREAD);
newtio.c_cflag &= ~(PARENB | PARODD); // No parity
newtio.c_cflag &= ~CRTSCTS; // No hardware handshake
newtio.c_cflag &= ~CSTOPB; // 1 stopbit
newtio.c_iflag = IGNBRK;
newtio.c_iflag &= ~(IXON | IXOFF | IXANY); // No software handshake
newtio.c_lflag = 0;
newtio.c_oflag = 0;
newtio.c_cc[VTIME] = 1;
newtio.c_cc[VMIN] = 60;
if (tcsetattr(serial_fd, TCSANOW, &newtio) == -1) {
cout << "tcsetattr failed" << endl;
return -1;
}
tcflush(serial_fd, TCIOFLUSH); // Clear IO buffer
return serial_fd;
}
void otherselect(){
fd_set readfs;
timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
char * buffer = new char[15];
int _fd = open_port();
FD_ZERO(&readfs);
FD_SET(_fd, &readfs);
select(_fd+1, &readfs, NULL, NULL, &tv /* no timeout */);
if (FD_ISSET(_fd, &readfs))
{
int r = read(_fd, buffer, 15);
if(r == -1){
cout << strerror(errno) << endl;
}
cout << buffer << endl;
}
else{
cout << "data not available" << endl;
}
close(_fd);
sleep(1);
}
int main() {
while(1){
otherselect();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 1
当您使用 read() 时,您不会得到以 null 结尾的字符串,因此
cout<<buffer<<endl
Run Code Online (Sandbox Code Playgroud)
显然是个坏主意。做一个,
buffer[r]='\0' #(provided r<15)
Run Code Online (Sandbox Code Playgroud)
在打印出来之前。