2017-08-12 40 views
0

我想通過串行連接使用read()函數。串行讀()沒有返回一個值沒有數據接收

我初始化串行端口具有下列設置:

bool HardwareSerial::begin(speed_t speed) { 


    int USB = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY); 

    if (USB == 1) { 

     std::cout << "\n Error! in Opening ttyUSB0\n" << std::endl; 
    } else { 

     std::cout << "\n ttyUSB0 Opened Successfully\n" << std::endl; 
    } 

    struct termios tty; 
    struct termios tty_old; 
    memset(&tty, 0, sizeof tty); 

    // Error Handling 
    if (tcgetattr(USB, &tty) != 0) { 
     std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl; 
    } 

    //Save old tty parameters 
    tty_old = tty; 

    // Set Baud Rate 
    cfsetospeed(&tty, (speed_t) speed); 
    cfsetispeed(&tty, (speed_t) speed); 

    // Setting other Port Stuff 
    tty.c_cflag &= ~PARENB; // Make 8n1 
    tty.c_cflag &= ~CSTOPB; 
    tty.c_cflag &= ~CSIZE; 
    tty.c_cflag |= CS8; 

    tty.c_iflag &= ~(IXON | IXOFF | IXANY); 
    tty.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG); 

    tty.c_cflag &= ~CRTSCTS; // no flow control 
    tty.c_cc[VMIN] = 1; // read doesn't block 
    tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout 
    tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines 

    // Make raw 
    cfmakeraw(&tty); 

    //Flush Port, then applies attributes 
    tcflush(USB, TCIFLUSH); 
    if (tcsetattr(USB, TCSANOW, &tty) != 0) { 
     std::cout << "Error " << errno << " from tcsetattr" << std::endl; 
    } 

    _USB = USB; 

    return true; 

} 

然後我定期調用類成員讀()函數調用流中讀取:

int HardwareSerial::read() { 

    int n = 0; 
    char buf; 

    n = ::read(_USB, &buf, 1); 

    std::cout << std::hex << static_cast<int> (buf) << " n:"; 
    std::cout << n << std::endl; 

} 

雖然端口接收數據的讀()按預期工作並打印傳入字節。但是,如果我停止發送字節,程序會掛起,直到某些字節未收到。 我期望::讀取將返回0,但它不會返回任何內容並等待傳入​​的數據。在收到新數據後,程序繼續工作,並且:: read返回1;

那麼我在配置中錯過了什麼? 我試過不同的VMIN和VTIME,但結果是一樣的。

回答

4

您正在以阻擋方式從USB讀取數據,例如,如果沒有可用的數據,則呼叫被阻止,並且在數據到達之前進程不會進行任何進展。

比可以做到的,你可以設置描述符NON-BLOCKING模式,這些方針爲:

int flags = fcntl(_USB, F_GETFL, 0); 
fcntl(_USB, F_SETFL, flags | O_NONBLOCK) 

現在比你會試圖讀取,你可以這樣做:

int count; 
char buffer; 
count = read(_USD, buf, 1); 
// Check whenever you succeeded to read something 
if(count >=0) { 
    // Data is arrived 
} else if(count < 0 && errno == EAGAIN) { 
    // No Data, need to wait, continue, or something else. 
} 

您也可以使用select函數來檢查設備描述符是否準備好讀取。