/***************************************************************************
by Diego Martinez
***************************************************************************/
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <iostream>
#include <getopt.h>
/*
* 'open_port()' - Open serial port 1.
*
* Returns the file descriptor on success or -1 on error.
*/
int open_port(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
/*
* Could not open the port.
*/
perror("open_port: Unable to open /dev/ttyS0 - ");
}
else
{
fcntl(fd, F_SETFL, 0);
//The FNDELAY option causes the read function to return 0 if no characters are available on the port. To restore normal (blocking) behavior, call fcntl() without the FNDELAY option:
fcntl(fd, F_SETFL, FNDELAY);
//configuramos el puerto
struct termios options;
// Get the current options for the port...
tcgetattr(fd, &options);
// Set the baud rates to 19200...
cfsetispeed(&options, B9600); //baudios de entrada
cfsetospeed(&options, B9600); //baudios de salida
//Enable the receiver and set local mode...
options.c_cflag |= (CLOCAL | CREAD);
// Set the new options for the port...
tcsetattr(fd, TCSANOW, &options);
}
return (fd);
}
int main()
{
int hcom=open_port();
while(true)
{
int bytes;
ioctl(hcom, FIONREAD, &bytes);
if (bytes>0)
printf("Datos!\r\n");
}
close(hcom);
return 0;
}