【问题标题】:Serial port won't open in linux ubuntulinux ubuntu 打不开串口
【发布时间】:2014-03-27 16:57:14
【问题描述】:

我无法在 linux ubuntu 中打开串口开始通信。我试过这个:

int OpenPort(void) {

int fd; 

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

if(fd == -1)
{
  printf("Failed to open port.\n");
}
else
{
    fcntl(fd, F_SETFL, 0);
    printf("Opened!\n");
}

return(fd);
}

int main()
{
  int x = OpenPort();
  printf("%i\n", x);

  exit(0);
}

我是 linux 新手,在网上找到了这段代码,但它对我不起作用。

【问题讨论】:

  • 错误是什么?尝试将printf("Failed to open port.\n") 替换为printf("Failed to open port: %s.\n", strerror(errno))perror("Failed to open port.")
  • 当系统调用失败时,您应该打印包含错误代码的errno 的值。您可以使用strerror 函数获得一个漂亮的可打印字符串。也可以使用perror函数直接打印消息。
  • 错误是权限被拒绝

标签: c linux ubuntu serial-port communication


【解决方案1】:

您需要以超级用户/root 身份运行才能访问 linux 中的串行端口。尝试以sudo 运行您的二进制文件。如果您可以验证这是问题所在,但您不希望您的进程由 root 用户运行,那么您可以在代码中使用一些选项来获得 root 权限。这个答案可能对阅读 How to programmatically gain root privileges?

有用

【讨论】:

  • 它可以与 sudo 一起使用,但是没有它如何运行呢?如何获得权限?我以管理员身份运行 ubuntu。
  • @user2081328 查看我在编辑中链接到的答案。
  • @user2081328 顺便说一句,我注意到您在 SO 上问了 13 个问题,但没有接受任何答案。如果您发现某个答案解决了您的问题,您可以接受它。这有助于将来查看您的问题的人了解哪个是最佳解决方案。
猜你喜欢
  • 2017-03-23
  • 1970-01-01
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-01
  • 1970-01-01
相关资源
最近更新 更多