views:

109

answers:

1

I'm running Ubuntu 9.10 and I seem to be having trouble with termios. So I can start minicom open the serial port at 57600 Baud, 8N1, no hardware or software flow control and it works great. I type in @17 5 and my device responds. When I try to set up my serial port in my C++ code I don't get a response. I know that the software is communicating to the port because an led turns on.

Here is my main:

int main(void)
{
  int fd; /* File descriptor for the port */

  fd = open("/dev/keyspan1", O_RDWR | O_NOCTTY | O_NDELAY);
  if (fd == -1)
    {
      /*
       * Could not open the port.
       */

      perror("open_port: Unable to open /dev/ttyS0 - ");
    }
  else
    fcntl(fd, F_SETFL, 0);

  /*****************************CHANGE PORT OPTIONS***************************/
  struct termios options;

  /*
   * Get the current options for the port...
   */

  tcgetattr(fd, &options);

  /*
   * Set the baud rates to 57600...
   */

  cfsetispeed(&options, B57600);
  cfsetospeed(&options, B57600);

  /*
   * Enable the receiver and set local mode...
   */

  options.c_cflag |= (CLOCAL | CREAD);

  /*
   * Set the new options for the port...
   */


  tcsetattr(fd, TCSANOW, &options);
  /***********************************END PORT OPTIONS***********************/

  int n;
  n = write(fd, "@17 5 \r", 7);
  if (n < 0)
    fputs("write() of 8 bytes failed!\n", stderr);

  char buff[20];

  sleep(1);

  n = read(fd, buff, 10);

  printf("Returned = %d\n", n);

  close(fd);

  return(0);
}

Any suggestions would be appreciated. Thanks.

A: 

You probably need to initialize your terminal to raw mode. I suggest you use cfmakeraw() to initialize the term options structure. Among others, cfmakeraw will make sure that flow control is disabled, parity checks are disabled, and input is available character by character.

cfmakeraw is non-Posix. If you're concerned with portability, look up the cfmakeraw manpage for the settings it is making.

Fabian