Wan*_*ist 4 c++ linux serial-port
我正在编写一个程序来控制与卫星通信的铱星调制解调器。发送每个AT命令后,调制解调器会发回一个回复(取决于命令),以指示命令成功。
现在,我已经实现了它,以便程序在将每个命令传输到调制解调器之间仅等待10秒钟,但这有点冒险,因为在未成功解释命令的情况下,它不允许进行错误处理。我知道如何读取串行输入的唯一方法是使用while(fgets( , ,)),所以我想知道如何让程序等待调制解调器通过串行端口的答复,并在发送下一个命令而不是发送命令之前检查其内容。具有统一的延迟。
我正在使用Linux OS。
FILE *out = fopen(portName.c_str(), "w");//sets the serial port
for(int i =0; i<(sizeof(messageArray)/sizeof(messageArray[0])); i++)
{
//creates a string with the AT command that writes to the module
std::string line1("AT+SBDWT=");
line1+=convertInt( messageArray[i].numChar);
line1+=" ";
line1+=convertInt(messageArray[i].packetNumber);
line1+=" ";
line1+=messageArray[i].data;
line1+=std::string("\r\n");
//creates a string with the AT command that initiates the SBD session
std::string line2("AT+SBDI");
line2+=std::string("\r\n");
fputs(line1.c_str(), out); //sends to serial port
usleep(10000000); //Pauses between the addition of each packet.
fputs(line2.c_str(), out); //sends to serial port
usleep(10000000);
}
Run Code Online (Sandbox Code Playgroud)
在与串行端口对应的文件描述符上使用select或poll,当描述符准备好读取时,它将返回。
像这样:
int fd = fileno(stdin); /* If the serial port is on stdin */
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
struct timeval timeout = { 10, 0 }; /* 10 seconds */
int ret = select(fd+1, &fds, NULL, NULL, &timeout);
/* ret == 0 means timeout, ret == 1 means descriptor is ready for reading,
ret == -1 means error (check errno) */
Run Code Online (Sandbox Code Playgroud)