讀取 /dev/ttyUSB0 失敗?

讀取 /dev/ttyUSB0 失敗?

我有一個 GPS 設備連接到 /dev/ttyUSB0 我編寫了一個簡單的代碼來從中讀取數據,但讀取總是失敗我不知道問題出在哪裡這是我的代碼你可以幫助我嗎:)。

#include<iostream>
#include<fstream>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>

using namespace std;
int read_port(void) 
{
int fd;
fd = open("dev/ttyUSB0" , O_RDWR | O_NOCTTY | O_NDELAY);
if (fd ==-1) 
{
    perror("open_port: Unable to open /dev/ttyUSB0 - ");

}

   char buffer[32];
    int n = read(fd, buffer, sizeof(buffer));
    if (n < 0)
        fputs("read failed!\n", stderr);
    return (fd);
}

int main()
{
     read_port();
}

答案1

/我想是因為你前面缺少一個dev

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

如果我是你,我會為此創建一個變量

/dev/ttyUSB0 

這樣open和 就error可以顯示相同的檔名。節省混亂。

相關內容