2013-06-22 24 views
0

我有一個用C語言編寫的簡單程序,它使用termios向Raspberry Pi UART發送基本字符串,並嘗試讀取和輸出響應。 Raspberry Pi上的Rx和Tx引腳用跳線連接,因此應立即收到發送的內容。Raspberry Pi UART程序在C中使用termios接收垃圾(Rx和Tx直接連接)

儘管程序輸出成功地發送和接收了5個字符('Hello'),但試圖打印緩衝區的內容只會產生一個或兩個垃圾字符。

程序:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
#include <fcntl.h> 
#include <termios.h> 

int main(int argc, char* argv[]) { 

    struct termios serial; 
    char* str = "Hello"; 
    char buffer[10]; 

    if (argc == 1) { 
     printf("Usage: %s [device]\n\n", argv[0]); 
     return -1; 
    } 

    printf("Opening %s\n", argv[1]); 

    int fd = open(argv[1], O_RDWR | O_NOCTTY | O_NDELAY); 

    if (fd == -1) { 
     perror(argv[1]); 
     return -1; 
    } 

    if (tcgetattr(fd, &serial) < 0) { 
     perror("Getting configuration"); 
     return -1; 
    } 

    // Set up Serial Configuration 
    serial.c_iflag = 0; 
    serial.c_oflag = 0; 
    serial.c_lflag = 0; 
    serial.c_cflag = 0; 

    serial.c_cc[VMIN] = 0; 
    serial.c_cc[VTIME] = 0; 

    serial.c_cflag = B115200 | CS8 | CREAD; 

    tcsetattr(fd, TCSANOW, &serial); // Apply configuration 

    // Attempt to send and receive 
    printf("Sending: %s\n", str); 

    int wcount = write(fd, &str, strlen(str)); 
    if (wcount < 0) { 
     perror("Write"); 
     return -1; 
    } 
    else { 
     printf("Sent %d characters\n", wcount); 
    } 

    int rcount = read(fd, &buffer, sizeof(buffer)); 
    if (rcount < 0) { 
     perror("Read"); 
     return -1; 
    } 
    else { 
     printf("Received %d characters\n", rcount); 
    } 

    buffer[rcount] = '\0'; 

    printf("Received: %s\n", buffer); 

    close(fd); 
} 

輸出:

Opening /dev/ttyAMA0 
Sending: Hello 
Sent 5 characters 
Received 5 characters 
Received: [garbage] 

我不能看到與自己代碼的任何重大問題,但我可能是錯的。我可以使用連接相同設置的PuTTY成功發送和接收字符,因此它不能成爲硬件問題。雖然我沒有在PuTTY上試過,但試圖用這個程序連接任何小於115200波特的數據都不會收到任何結果。

我哪裏錯了?

+0

除了通過@parkydr適用的答案,你可能會在不回送,並連接到一個真實的設備有問題。清除* termios *成員是不好的編碼習慣。正確的[POSIX方法](http://www.cmrr.umn.edu/~strupp/serial.html)可以在不修改任何其他位或結構成員的情況下按位清除或設置每個必要的標誌。在你的代碼中,'tcgetattr()'調用是多餘的。你應該像'tcgetattr()'一樣檢查來自'tcsetattr()'的返回碼。 – sawdust

+0

@sawdust這通常只是爲了確保在編寫程序之前我已經掌握了基礎知識,但我會考慮您的建議。 – kourosh

回答

2
int wcount = write(fd, &str, strlen(str)); 
int rcount = read(fd, &buffer, sizeof(buffer)); 

在這些行中,buffer/str已經是指針。你傳遞一個指針指向一個指針。

該行應該是:

int wcount = write(fd, str, strlen(str)); 
int rcount = read(fd, buffer, sizeof(buffer)); 
+0

我知道我會在某個地方犯了一個愚蠢的錯誤,完美地工作,謝謝! – kourosh