
#include <stdio.h>
#include <fcntl.h>       /* File Control Definitions           */
#include <termios.h>     /* POSIX Terminal Control Definitions */
#include <unistd.h>      /* UNIX Standard Definitions          */
#include <errno.h>       /* ERROR Number Definitions           */
#include <sys/ioctl.h>   /* ioctl()                            */
#include <ctype.h>


void testSend(int fd);



int main(void)
{
  int fd;     /*File Descriptor*/
  int status;
  int i;
  struct termios options;

  fd = open("/dev/ttyUSB0",O_RDWR | O_NOCTTY ); //Opening the serial port
  tcgetattr(fd, &options);
  cfsetispeed(&options, B19200);
  cfsetospeed(&options, B19200);

  options.c_cflag &= ~PARENB;
  options.c_cflag &= ~CSTOPB;
  options.c_cflag &= ~CSIZE;
  options.c_cflag |= CS8;

  options.c_cflag &= ~CRTSCTS; /* disable HW flow control */
  options.c_iflag &= ~(IXON | IXOFF | IXANY); /* disable SW flow control */

  options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /* raw input */

  tcsetattr(fd, TCSANOW, &options);

  for (i=0;; i++) {
    char r;

    testSend(fd);
    r=getchar(); //To view the change in status pins before closing the port
    if (r=='q' || r=='Q')
      break;
  }

  close(fd);
  return 0;
}




void testSend(int fd)
{
  int status;
  const unsigned char bufOut[2]="B";
  unsigned char bufIn[256];
  ssize_t len;
  
  ioctl(fd,TIOCMGET,&status); /* GET the State of MODEM bits in Status */
  status |= TIOCM_DTR;        // Set the DTR pin
  ioctl(fd, TIOCMSET, &status);

  usleep(10);

  write(fd, bufOut, 1);

  usleep(10);

  ioctl(fd,TIOCMGET,&status); /* GET the State of MODEM bits in Status */
  status &= ~ TIOCM_DTR;        // Set the DTR pin HIGH (cave: signals inverted!)
  ioctl(fd, TIOCMSET, &status);

#if 1
  len=read(fd, bufIn, sizeof(bufIn)-1);
  if (len<1) {
    fprintf(stderr, "ERROR on read\n");
  }
  else {
    ssize_t i;

    fprintf(stderr, "Received: ");
    for(i=0; i<len; i++) {
      fprintf(stderr, "%02x", bufIn[i]);
    }
    fprintf(stderr, "  ");
    for(i=0; i<len; i++) {
      char j;

      j=bufIn[i];
      if (iscntrl(j))
	j='?';
      fprintf(stderr, "%c", j);
    }
    fprintf(stderr, "\n");
  }
#endif
}




