Find the answer to your Linux question:
Results 1 to 2 of 2
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    Writing and reading from a serial port


    I am working on a project that will basically write some data to 8250 serial port (/dev/ttyS0) and then read back the same data. My understanding is if I write something, it will stored in a buffer and then if I read back, I should be able to read what I just wrote. However, I am having issues where I can write successfully to a serial port but when I check for # of bytes available in the input buffer, it returns 0. So basically, my write does not flush. Can you tell me where the problem..? Here is my code snippet.

    #include <termios.h>
    #include <stdio.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <sys/signal.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <sys/time.h>
    #include <stdlib.h>
    #include <sys/ioctl.h>
    int main()
        int fd, res, sen;
        int i;
        struct termios oldtio, newtio;
        char buf[] = "hello";
        int bytes, total;
    	 fd = open("/dev/ttyS0",O_RDWR | O_NONBLOCK | O_SYNC);
        if (fd < 0) { perror("error"); return EXIT_FAILURE; }
        fcntl( fd, F_SETFL, O_NONBLOCK );
        newtio.c_cflag =  CLOCAL | CREAD;
        newtio.c_iflag = IGNPAR | ICRNL;
        newtio.c_oflag = 0;
        newtio.c_lflag = ICANON;
        newtio.c_cc[VMIN] = 0;
        newtio.c_cc[VTIME] = 10;
        tcflush(fd, TCIFLUSH);
        tcsetattr( fd, TCSANOW, &newtio );
            sen = write( fd, buf, sizeof(buf) );
            printf("No. of bytes written  = %d\n", sen);
            tcsetattr(fd, TCSAFLUSH, &newtio);
            total =ioctl(fd, FIONREAD, &bytes);
            printf("No. of bytes in the input buffer = %d\n", total);
      return 0;
    Any help will be highly appreciated.

    Last edited by MikeTbob; 12-03-2011 at 07:00 AM. Reason: Added Code Tags

  2. #2
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    I can be found either 40 miles west of Chicago, in Chicago, or in a galaxy far, far away.
    Buffering is one thing. Reading is another. The only way you could do that would be to have a cable that connects the serial port back to itself.
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts