0

我正在尝试在 Raspberry Pi 中使用串行通信。我找到了这个链接。我只对代码进行了一次更改,并将缓冲区值增加到 30。这是我编辑的代码:-

#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[30];

    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_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));
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));
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);
}

我短接 Rx 和 Tx 引脚并运行此代码。我应该收到“你好”,但我得到了这个:-

Received: pi@raspberrypi:~$ Hello

所以,很明显我正在接收“你好”,但另外我正在自动传输

 pi@raspberrypi:~$

所以,请告诉我停止传输我的用户名。

4

0 回答 0