Skip to content

Instantly share code, notes, and snippets.

@houmei
Created September 2, 2012 17:06
Show Gist options
  • Save houmei/3601575 to your computer and use it in GitHub Desktop.
Save houmei/3601575 to your computer and use it in GitHub Desktop.
openPort (MacOSX)
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int openPort( const char *path, int speed, int bits, int parity, int stops, int openFlags)
24 {
25 int fd, cflag ;
26 struct termios termattr ;
27
28 fd = open( path, openFlags ) ;
29 if ( fd < 0 ) return -1 ;
30
31 // build other flags
32 cflag = 0 ;
33 cflag |= ( bits == 7 ) ? CS7 : CS8 ; // bits
34 if ( parity != 0 ) {
35 cflag |= PARENB ; // parity
36 if ( parity == 1 ) cflag |= PARODD ;
37 }
38 if ( stops > 1 ) cflag |= CSTOPB ;
39
40 // merge flags into termios attributes
41 tcgetattr( fd, &termattr ) ;
42 termattr.c_cflag &= ~( CSIZE | PARENB | PARODD | CSTOPB ) ; // clear all bits and merge in our selection
43 termattr.c_cflag |= cflag | CLOCAL ; //
44
45 // set speed, split speed not support on Mac OS X?
46 cfsetispeed( &termattr, speed ) ;
47 cfsetospeed( &termattr, speed ) ;
48 // set termios
49 tcflush(fd,TCIFLUSH); // not needed?
50 tcsetattr( fd, TCSANOW, &termattr ) ;
51
52 return fd ;
53 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment