我有一个用C语言编写的简单程序,它使用termios向Raspberry Pi UART发送基本字符串,并尝试读取和输出响应。 Raspberry Pi上的Rx和Tx引脚用跳线连接,因此应立即收到发送的内容。Raspberry Pi UART程序在C中使用termios接收垃圾(Rx和Tx直接连接)
尽管程序输出成功地发送和接收了5个字符('Hello'),但试图打印缓冲区的内容只会产生一个或两个垃圾字符。
程序:
#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波特的数据都不会收到任何结果。
我哪里错了?
除了通过@parkydr适用的答案,你可能会在不回送,并连接到一个真实的设备有问题。清除* termios *成员是不好的编码习惯。正确的[POSIX方法](http://www.cmrr.umn.edu/~strupp/serial.html)可以在不修改任何其他位或结构成员的情况下按位清除或设置每个必要的标志。在你的代码中,'tcgetattr()'调用是多余的。你应该像'tcgetattr()'一样检查来自'tcsetattr()'的返回码。 – sawdust
@sawdust这通常只是为了确保在编写程序之前我已经掌握了基础知识,但我会考虑您的建议。 – kourosh