strange behavior with setting GPS serial port speed
I have a USB gps that uses a serial interface.
It's from deluo.com, and the chipset in this case is Sony, but the same thing is true of other GPS systems I've been trying.
In order to read it, they told me to:
cat </dev/ttyUSB0
and then in another shell:
stty -F /dev/ttyUSB0 4800
Sure enough, it works.
But I wanted to do this programmatically. I tried writing code in C using termios.h
It didn't work, so I figured there was something stty was doing that my code wasn't doing. I got the source code to stty and walked through it, and all I can see are the same calls. I include the code here, it's pretty small:
#include <termios.h>
#include <sys/fcntl.h>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
char* deviceName = argv[1];
struct termios tty;
int fd = open (deviceName, O_RDONLY | O_NONBLOCK);
int fdflags;
if ((fdflags = fcntl (fd, F_GETFL)) == -1) {
cerr << "error!\n";
}
if (tcgetattr (fd, &tty)) {
cerr << "screwed up serial port!\n";
}
// error (EXIT_FAILURE, errno, "%s", device_name);
cfsetospeed (&tty, B4800);
cfsetispeed (&tty, B4800);
tcsetattr (fd, TCSADRAIN, &tty);
}
The code, as it turns out, does work, but only in the sense that stty works. That is, I have to write code to open the gps, then in a subshell run the above, and it will (at least on the Mac where I just tested it) start showing the incoming data. But if I try to write a single code where I Open the file, set the baud rate, then read, it doesn't work. If I open the file, do a read, then attempt to set the baud rate, it hangs. I guess I could do it in a background thread, but the real question is why should i have to?
The only way I have gotten this to work in a program is to write perl that first opens the file, and then executes stty in a subshell. And it has to be IN THAT ORDER.
The exact same story is true on the Mac, except that the device names are different since it's BSD, /dev/cu.usbserial
Can anyone tell me what I'm doing wrong, how I can write code that will do this.
|