繁体   English   中英

C ++串行通信

[英]C++ Serial Communication

我正在运行Ubuntu 9.10,我似乎遇到了使用termios的问题。 所以我可以启动minicom打开57600 Baud,8N1的串口,没有硬件或软件流控制,效果很好。 我键入@ 17 5,我的设备响应。 当我尝试在我的C ++代码中设置我的串口时,我没有得到回复。 我知道软件正在与端口进行通信,因为led已打开。

这是我的主要内容:

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);
}

任何建议,将不胜感激。 谢谢。

您可能需要将终端初始化为原始模式。 我建议你使用cfmakeraw()初始化术语选项结构。 其中,cfmakeraw将确保禁用流量控制,禁用奇偶校验检查,并逐个输入输入。

cfmakeraw是非Posix。 如果您关注可移植性,请查看cfmakeraw联机帮助页以了解其正在进行的设置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM