Last active
April 29, 2016 02:23
-
-
Save vo/2c7c4564d388fcc134a8cdd701c71381 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*------------------------------------------------------------------------------ | |
* Open a serial port to the MAV with the given port name and baud rate. | |
* returns: the file descriptor, or < 0 if error. | |
*/ | |
static int mav_serial_open(const char *port_name, uint32_t const baud_rate) | |
{ | |
// attempt to open the port. | |
int fd = open(port_name, O_RDWR | O_NOCTTY | O_NDELAY); | |
if (fd < 0) { | |
fprintf(stderr, "ERROR: Could not open() serial port %s.\n", port_name); | |
return fd; | |
} | |
// configure file reading. | |
fcntl(fd, F_SETFL, 0); | |
// set baud rate from parameter | |
speed_t baud; | |
switch (baud_rate) { | |
case 115200: | |
baud = B115200; | |
break; | |
default: | |
baud = B57600; | |
break; | |
} | |
// get previous options | |
struct termios options; | |
tcgetattr(fd, &options); | |
// set baud rate in options | |
int ret = cfsetispeed(&options, baud); | |
if (ret < 0) { | |
fprintf(stderr, "ERROR: Couldn't set speed for serial port %s\n", port_name); | |
return ret; | |
} | |
ret = cfsetospeed(&options, baud); | |
if (ret < 0) { | |
fprintf(stderr, "ERROR: Couldn't set speed for serial port %s\n", port_name); | |
return ret; | |
} | |
// set other flags in options | |
// (raw i/o for 8N1) | |
options.c_cflag &= ~(CSIZE | PARENB); | |
options.c_cflag |= CS8 | CLOCAL | CREAD | CRTSCTS; | |
options.c_lflag = ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); | |
options.c_oflag = ~(OCRNL | ONLCR | ONLRET | ONOCR | OFILL | OPOST); | |
options.c_iflag = ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | | |
INPCK | ICRNL | IXON); | |
options.c_cc[VMIN] = 1; | |
// set attributes for serial port. | |
ret = tcsetattr(fd, TCSAFLUSH, &options); | |
if (ret < 0) { | |
fprintf(stderr, "ERROR: Can't set attribs for serial port %s\n", port_name); | |
return ret; | |
} | |
return fd; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment