调用两次时,write()到串口失败

时间:2014-05-04 22:25:01

标签: c linux serial-port

我正在尝试将char数组写入串口两次。由于某种原因我第二次调用write()它失败了,我不明白为什么。奇怪的是第一次写成功。

这是我的写作功能:

void write_port()
{
  unsigned char writeBuffer[5];
  int i;
  size_t len;

  writeBuffer[0] = 0x00;
  writeBuffer[1] = 0x01;
  writeBuffer[2] = 0x02;
  writeBuffer[3] = 0x03;
  writeBuffer[4] = 0x04;  

  len = sizeof(writeBuffer);

  for (i=0; i < len; i++)
  {
    printf("Write: %x\n", writeBuffer[i]);
  }

  //First Write:
  int n = write(fd, writeBuffer, len);
  if (n < 0)
    fputs("Serial Port Write Failed!\n", stderr);
  else
    printf("Wrote %0d bytes to serial port\n", n);

  //Second Write:
  n = write(fd, writeBuffer, len);
  if (n < 0)
    fputs("Serial Port Write Failed!\n", stderr);
  else
    printf("Wrote %0d bytes to serial port\n", n);  
}

这是我配置端口的地方:

int open_port(void)
{
  struct termios options;

  fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);

  bzero(&options, sizeof(options));   // set everything to 0 

  if (fd != -1)
  {
    printf("Serial Port Open\n");

    tcgetattr(fd, &options_original);
    tcgetattr(fd, &options);
    cfsetispeed(&options, B460800);
    cfsetospeed(&options, B460800);
    options.c_cflag |= (CLOCAL | CREAD); /* Enable the receiver and set local mode */
    options.c_cflag &= ~ECHO; // Disable echoing of input characters
    options.c_cflag &= ~ECHOE;
    options.c_cflag &= ~PARENB; // parity disabled
    options.c_cflag &= ~CSTOPB; // 1 stop bit
    options.c_cflag &= ~CSIZE;  // Mask the character size bits
    options.c_cflag |=  CS8;    // 8 data bits    
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);  /* Raw Input Mode */

    if (tcsetattr(fd, TCSANOW, &options))    /* Set the new options for the port */
    {
      perror("could not set the serial settings!");
      return -1;
    }
  }
  else
  {
    /* Could not open the port */
    perror("open_port: Unable to open /dev/ttyUSB0 - ");
  }

  return (fd);
}

最后这是我的控制台输出。

Serial Port Open
Flushing IO Buffers
Write: 0
Write: 1
Write: 2
Write: 3
Write: 4
Wrote 5 bytes to serial port
Serial Port Write Failed!
Serial Port Closed

所以由于某种未知的原因,我从第二次写()中得到-1,并且完全不知道为什么,世界上有什么可能导致这种情况?

2 个答案:

答案 0 :(得分:2)

我认为您的发送缓冲区已满,并且您正在使用非阻塞套接字,这意味着该进程只返回“资源暂时不可用错误”,而不是像阻塞套接字一样等待缓冲区清除。有关详细信息,请参阅此主题:What can cause a “Resource temporarily unavailable” on sock send() command

答案 1 :(得分:0)

写入系统调用如果失败则设置errno变量。您可以检查以获取写入失败原因的确切详细信息。另外,您可以参考该项目的linux本机代码,了解如何实现写入https://github.com/RishiGupta12/serial-communication-manager