3

我有一个用 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);
}

输出:

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

我自己看不到代码有任何重大问题,但我可能错了。我可以使用连接相同设置的 PuTTY 成功发送和接收字符,所以这不是硬件问题。虽然我没有在 PuTTY 中尝试过,但尝试使用该程序连接低于 115200 波特的任何东西都不会收到任何内容。

我哪里错了?

4

1 回答 1

5
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));
于 2013-06-23T17:30:41.320 回答