树莓派UART程序使用termios接收垃圾(Rx和Tx直接连接)

kou*_*osh 3 serial-port termios garbage uart raspberry-pi

我有一个用 C 编写的简单程序,它使用 termios 将基本字符串发送到 Raspberry Pi UART 并尝试读取和输出响应。Raspberry Pi 上的 Rx 和 Tx 引脚通过跳线连接,因此应立即接收发送的任何内容。

尽管程序输出它成功发送和接收所选字符串('Hello')的 5 个字符,尝试打印缓冲区的内容只会产生一两个垃圾字符。

该程序:

#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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

Opening /dev/ttyAMA0
Sending: Hello
Sent 5 characters
Received 5 characters
Received: [garbage]
Run Code Online (Sandbox Code Playgroud)

我自己看不出代码有任何重大问题,但我可能是错的。我可以使用连接相同设置的 PuTTY 成功发送和接收字符,因此这不是真正的硬件问题。虽然我还没有在 PuTTY 中尝试过,但尝试使用此程序连接任何低于 115200 波特的设备将导致什么也收不到。

我哪里错了?

par*_*ydr 5

int wcount = write(fd, &str, strlen(str));
int rcount = read(fd, &buffer, sizeof(buffer));
Run Code Online (Sandbox Code Playgroud)

在这些行中, buffer/str 已经是指针。您正在传递一个指向指针的指针。

这些行应该是:

int wcount = write(fd, str, strlen(str));
int rcount = read(fd, buffer, sizeof(buffer));
Run Code Online (Sandbox Code Playgroud)