Friday, March 27, 2009

Linux Serial port programming


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>

#define BAUDRATE B9600
#define MODEMDEVICE "/dev/ttyS0"
#define _POXSIX_SOURCE 1
#define FALSE 0
#define TRUE 1

volatile int STOP=FALSE;

int main()
{
int fd, c, res;
struct termios oldtio, newtio;
char buf[255];

//fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY | O_NDELAY);
//fd = open(MODEMDEVICE, O_RDWR | O_NDELAY);
fd = open(MODEMDEVICE, O_RDWR );
if(fd < 0){
perror("Cannot open device");
exit(-1);
}

tcgetattr(fd, &oldtio);

bzero(&newtio, sizeof(newtio));

newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;

newtio.c_lflag = 0;

newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 5;

tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &newtio);

while(STOP == FALSE){
res = read(fd, buf, 255);
buf[res] = '\0';
printf("%s -> %d\n", buf, res);
if(buf[0] == 'z') STOP=TRUE;
}
tcsetattr(fd, TCSANOW, &oldtio);

return 0;
}

No comments: