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

I am writing a program for controlling an Iridium modem that communicates with a satellite. After sending each AT command, the modem sends a response (depending on the command) to indicate that the command was successful.

Now I have implemented it, so 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 error handling if the command is not successfully interpreted. The only way I know how to read serial input is while(fgets( , ,)) , so I wonder how I can get the program to wait for a response from the modem via the serial port and check that it is before the next command instead of a uniform delay .

I am using 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); } 
+4
source share
2 answers

Use select or poll in the file descriptor corresponding to the serial port that will return when the descriptor is ready to be read.

Something like that:

 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) */ 
+4
source

To stay as close to your model as possible, you can do a couple of things:

1) Use a simple file descriptor (via open ()). You should also use read () and write () to communicate with the serial port.

2) Using 1 above allows you to use select to see if something is ready for writing or reading.

It will also allow you to move the connection to the modem to another thread if there are other things that your program should do ...

I recently did something very simulated with the HF Radio modem only and used the Boost ASIO library to communicate over the serial port.

This may help you if this is an option.

+2
source

All Articles