/* sin.c - simple serial input code */
/* based on code at: http://www.easysw.com/~mike/serial/ */
/* designed to be used with sout */
/* checks ttyC0 for input - prints it and exits when */
/* it gets a Z as the first character in a string */

#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);

    /* set some port parameters */
    tcgetattr(sfd, &o_opts);
    n_opts=o_opts;
    /*turn off echo*/
    n_opts.c_lflag &= ~(ECHO);
    /*apparently handles \n correctly*/
    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);
        for (i=0;i<=n;i++)
            printf("char %d is %c or %d.\n",i,buf[i],buf[i]);
        }
    while (buf[0]!='Z');

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

int open_port(void)

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

   return (fd);
 }
