Thread: Reading and writing to a serial port

  1. #1
    Registered User
    Join Date
    Aug 2006

    Reading and writing to a serial port


    I'm new here, but I've spent the last couple hours searching your archives, and this llooks like a really terrific forum!!!!

    I am working on a project that has my computer communicating with a microcontroller over an RS-232 connection. I've got the program on the microcontroller working flawlessly with minicom at 9600 8N1. I should say that I am programming in C on an OSX/BSD unix machine.

    i've just spent the day trying to write a C program to communicate read and write to the serial port, so I don't have to use minicom, and I and pretty much baffeled.

    The program on the microcontroller send out a short text string, and then will listen on the serial port and repeat back any thing you type on it... character by character... forever.

    So, I've been following the instruction in Serial Programming Guide for POSIX Operating Systems

    and here is the code that I've written... though it is mainly copied from the text...

    #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 */
     * 'open_port()' - Open serial port 1.
     * Returns the file descriptor on success or -1 on error.
    void main()
      int fd;  // File descriptor
      int n;
      fd = open_port();
      // Read the configureation of the port 
      struct termios options;
      tcgetattr( fd, &options );
      /* SEt Baud Rate */
      cfsetispeed( &options, B9600 );
      cfsetospeed( &options, B9600 );
      //I don't know what this is exactly 
      options.c_cflag |= ( CLOCAL | CREAD );
      // Set the Charactor size
      options.c_cflag &= ~CSIZE; /* Mask the character size bits */
      options.c_cflag |= CS8;    /* Select 8 data bits */
      // Set parity - No Parity (8N1)
      options.c_cflag &= ~PARENB;
      options.c_cflag &= ~CSTOPB;
      options.c_cflag &= ~CSIZE;
      options.c_cflag |= CS8;
      // Disable Hardware flowcontrol
      //  options.c_cflag &= ~CNEW_RTSCTS;  -- not supported
      // Enable Raw Input
      options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
      // Disable Software Flow control
      options.c_iflag &= ~(IXON | IXOFF | IXANY);
      // Chose raw (not processed) output
      options.c_oflag &= ~OPOST;
      if ( tcsetattr( fd, TCSANOW, &options ) == -1 )
        printf ("Error with tcsetattr = %s\n", strerror ( errno ) );
        printf ( "%s\n", "tcsetattr succeed" );
      fcntl(fd, F_SETFL, FNDELAY);
      // Write some stuff !!!
      n = write(fd, "ATZ\r", 4);
      if (n < 0)
        fputs("write() of 4 bytes failed!\n", stderr);
        printf ("Write succeed n = %i\n", n );
      for ( n = 0 ; n < 1000 ; n++)
      char *buf;
      n = read( fd, buf, 1 );
      if ( n == -1 )
          printf ( "Error = %s\n", strerror( errno ) );
      printf ( "Number of bytes to be read = %i\n", n );
      printf ( "Buf = %s\n", buf );
      close( fd );
    int open_port(void)
      int fd; /* File descriptor for the port */
      fd = open("/dev/tty.KeySerial1", O_RDWR | O_NOCTTY | O_NDELAY);
      if (fd == -1)
           * Could not open the port.
          perror("open_port: Unable to open /dev/ttyS0 - ");
        fcntl(fd, F_SETFL, FNDELAY);
      printf ( "In Open port fd = %i\n", fd);
      return (fd);
    Anyway, the problem I keep running into is that the read() returns the error "Resources temprarily unavailable." The write() seems to be doing fine, and I would expect that I would be able to read the 4 bytes that I just sent with the write(), but no.

    I don't really know what this means or what to do about it. I'm pretty stuck. I've shut down minicom, and rebooted the system so I know (I think) that minicom doesn't have any hold on the port.

    Any suggestions would be much apprecated.



  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > void main()
    main returns an int - see the FAQ

    > char *buf;
    1. This is declared in the middle of the code, so it isn't actually C code (not C89 code at least).
    2. It's a pointer not pointing anywhere, so dereferencing it is bad news for you.

    Since you're reading only 1 char at a time.
    char buff;
    n = read( fd, &buf, 1 );
    printf ( "Buf = %c\n", buf );

    > for ( n = 0 ; n < 1000 ; n++)
    You need to find a better way of making a delay. Assuming the compiler even left this code in, it would take very little time to run.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Aug 2006
    Thanks Bro!!!

    That did the trick! As I am pretty new to all this... and more or less just hacking through this as best I can, I really didn't know that stuff. Now I do. Giddy up!


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Serial port communcation and computer standby mode
    By MWAAAHAAA in forum Windows Programming
    Replies: 0
    Last Post: 07-09-2009, 10:38 AM
  2. serial port to poll on request
    By infineonintern in forum C++ Programming
    Replies: 2
    Last Post: 06-11-2009, 06:52 AM
  3. reading and writing from a COM port
    By abq_guy in forum C Programming
    Replies: 1
    Last Post: 04-20-2009, 04:57 PM
  4. Serial Port Issues (again!)
    By HalNineThousand in forum Linux Programming
    Replies: 6
    Last Post: 04-09-2008, 08:26 PM
  5. accessing my com port, writing and reading data
    By shoobsie in forum C Programming
    Replies: 7
    Last Post: 09-16-2005, 03:29 PM