/* sin.c - simple serial input code */
/* based on code at: http://www.easysw.com/~mike/serial/ */

#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 */

int open_port (void);

main ()
    {
    int sfd; /*serial port file descriptor*/
    struct termios o_opts, n_opts;
    ssize_t n;
    char buf[81];
    int i;

    sfd = open_port();
  
    /*make read return 0 bytes if none available*/
    /*fcntl(sfd, F_SETFL, FNDELAY);*/

    /*try to turn off echo*/
    tcgetattr(sfd, &o_opts);
    n_opts=o_opts;
    n_opts.c_iflag |= (IGNCR);
    tcsetattr(sfd, TCSANOW, &n_opts);

    do
        {
        while ((n=read(sfd,buf,80))<=0);
        buf[n]='\0';
        printf("I read %d bytes: %s\n",n,buf);
        }
    while (buf[0]!='Z');

    tcsetattr(sfd, TCSANOW, &o_opts);
    close (sfd);
    }

int open_port(void)

    {
    int fd; /*file descriptor*/
    
   fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
   if (fd == -1)
     fprintf(stderr, "open_port: Unable to open /dev/ttyS0 - %s\n",
             strerror(errno));

   return (fd);
 }
