Raspberry Pi UART programa em C usando termios recebe lixo (Rx e Tx estão conectados diretamente)

Eu tenho um programa simples escrito em C que usa termios para enviar uma string básica para o Raspberry Pi UART e tenta ler e enviar a resposta. Os pinos Rx e Tx no Raspberry Pi são conectados com um jumper para que o que for enviado seja imediatamente recebido.

Apesar da saída do programa que enviou com sucesso e recebeu 5 caracteres para a string escolhida ('Hello'), tentar imprimir o conteúdo do buffer produz apenas um ou dois caracteres de lixo.

O programa:

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

Saídas:

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

Eu não consigo ver nenhum grande problema com o código, mas posso estar errado. Eu posso enviar e receber com sucesso caracteres usando PuTTY conectado com as mesmas configurações, por isso não pode realmente ser um problema de hardware. Embora eu não tenha tentado em PuTTY, tentando se conectar com nada menos que 115200 baud com este programa irá resultar em nada ser recebido.

Onde eu estou errando?

questionAnswers(1)

yourAnswerToTheQuestion