/* siopocgloop.c - simple serial output code */
/* based on code at: http://www.easysw.com/~mike/serial/ */
/* sends atrp repeatedly out ttyC7 */
/* and prints response */

#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; 
    int n =0;
    int ni=0;
    int c;
    int i;
    int a=0;
    int b=0;
    char buf[80], ibuf[80];

    sfd = open_port(); /*open serial 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);
    /*set canonical (line at a time mode)*/
    n_opts.c_lflag |= ICANON;

    /*maps input CR to NL*/
    n_opts.c_iflag |= ICRNL;
    n_opts.c_iflag &= ~(IGNCR);
    n_opts.c_iflag &= ~(INLCR);

    /*accept \r as EOL in addition to \n*/
    n_opts.c_cc[VEOL]='\r';

    /*turn on output processing so other o_flags have an effect*/
    n_opts.c_oflag |= (OPOST);
    /*allow me to send a CR instead of NL if I want*/
    n_opts.c_oflag &= ~ONLRET;
    n_opts.c_oflag &= ~ONLCR;
    n_opts.c_oflag &= ~OCRNL;

    /*now baud rates*/
    cfsetispeed(&n_opts,B9600);
    cfsetospeed(&n_opts,B9600);
    /* now set to 8N1 */
    n_opts.c_cflag &= ~CSIZE;
    n_opts.c_cflag |= CS8;
    n_opts.c_cflag &= ~PARENB;
    n_opts.c_cflag &= ~CSTOPB;

    /*now make these settings active now*/
    tcsetattr(sfd, TCSANOW, &n_opts);

    while (1)
        {
        sprintf(buf,"atrp\n");
        if (write(sfd,buf,5)<0)
            fprintf(stderr,"write() of %d bytes failed.\n",n);
        n=0;
        while ((ni=read(sfd,ibuf,80))<=0);
        printf("Received:%s",ibuf);
        }

    close (sfd);
    }

int open_port(void)

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

   return (fd);
 }
