如何在程序的中间等待串口的输入

How to wait for input from the serial port in the middle of a program

本文关键字:等待 串口 输入 中间 程序      更新时间:2023-10-16

我正在写一个程序来控制与卫星通信的铱调制解调器。在每个AT命令发送后,modem发送一个应答(根据命令的不同)来表示命令成功。

现在我已经实现了它,以便程序在每个命令传输到调制解调器之间只等待10秒,但这有点冒险,因为它不允许在命令未成功解释的情况下进行错误处理。我知道如何读取串行输入的唯一方法是使用while(fgets( , ,)),所以我想知道我如何能够让程序等待调制解调器通过串行端口的回复,并在下一个命令发送之前检查它是什么,而不是有统一的延迟。

我用的是linux操作系统。

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("rn");
  //creates a string with the AT command that initiates the SBD session
  std::string line2("AT+SBDI");
  line2+=std::string("rn");
  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); 
}

对串行端口对应的文件描述符使用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) */

为了尽可能接近你的模型,你可以做几件事:

1)使用普通文件句柄(通过open())。然后,您将使用read()和write()与串行端口通信。

2)使用上面的1,然后让你使用select来查看是否有东西准备写入或读取。

如果您的程序有其他事情要做,这也允许您将与调制解调器的通信移动到另一个线程…

我最近用高频无线电调制解调器做了一些非常类似的事情,并使用Boost ASIO库进行串口通信。