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

空扰寡人 提交于 2019-12-23 12:58:01

问题


I am writing a program to control an Iridium modem that communicates with a satellite. After each AT command is sent, the modem sends a reply back (depending on the command) to indicate the command was successful.

Right now I have it implemented so that the program just waits 10 seconds between the transmission of each command to the modem, but this is a bit risky because it does not allow for error handling in case the command is not successfully interpreted. The only way I know how to read serial input is with while(fgets( , ,)), so I am wondering how I would be able to have the program wait for a reply from the modem over the serial port and check what it is before the next command is sent instead of having a uniform delay.

I'm using a 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); 
}

回答1:


Use select or poll on the file descriptor corresponding to the serial port, which will return when the descriptor is ready for reading.

Something like this:

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) */



回答2:


To stay as close to your model as you have you could do a couple of things:

1) Use a plain file handle ( via open() ). Also then you would use read() and write() to communicate with the serial port.

2) The use of 1 above then lets you use select to see if anything is ready to be written or read.

This would also allow you to move the communication with the modem to another thread if there are other things your program has to do...

I've recently done something very simular only with an HF Radio modem and used the Boost ASIO library for the serial port communication.

That could help you if it is an option.



来源:https://stackoverflow.com/questions/6656579/how-to-wait-for-input-from-the-serial-port-in-the-middle-of-a-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!