termios を使用して基本的な文字列を Raspberry Pi UART に送信し、応答を読み取って出力しようとする、C で記述された単純なプログラムがあります。Raspberry Pi の Rx ピンと Tx ピンはジャンパーで接続されているため、送信されたものはすべてすぐに受信されます。
プログラムは、選択した文字列 ('Hello') に対して 5 文字の送受信に成功したと出力しますが、バッファの内容を出力しようとすると、1 つか 2 つの文字化けが生成されます。
プログラム:
#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 ボー未満で接続しようとすると、何も受信されません。
どこが間違っていますか?