【问题标题】:C++ Serial CommunicationC++ 串行通信
【发布时间】:2013-02-27 06:09:44
【问题描述】:

我正在运行 Ubuntu 9.10,但似乎在使用 termios 时遇到了问题。 所以我可以启动 minicom,以 57600 波特,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);
}

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

【问题讨论】:

  • 也许您只需要在发送的字符串末尾包含一个 \n ?如果不是这样,您可以查看我在 Linux 下工作的 RS-232 代码:在此文件中搜索 tcsetattr (etc):public.msli.com/lcs/muscle/muscle/dataio/RS232DataIO.cpp(忽略 Windows 位,它们与您的情况无关)跨度>
  • 不应该需要\n...这是对无缓冲文件的无缓冲操作。
  • 这一切都取决于在串行线路的另一端正在监听什么,以及它是否正在寻找 \n,我想。
  • @Potatoswatter:未缓冲表示描述符的内核端处理。 write() 函数可以(并且确实,至少在 glibc 中)执行用户端缓冲,以限制发出的系统调用的数量。确保在每个 write() 块之后使用 fsync()。

标签: c++ serial-port


【解决方案1】:

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

cfmakeraw 不是 Posix。如果您担心可移植性,请查看 cfmakeraw 联机帮助页了解它所做的设置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多