使用termios的C语言中的Raspberry Pi UART程序接收垃圾(Rx和Tx直接连接) [英] Raspberry Pi UART program in C using termios receives garbage (Rx and Tx are connected directly)
问题描述
我有一个用C编写的简单程序,该程序使用termios将基本字符串发送到Raspberry Pi UART,并尝试读取和输出响应. Raspberry Pi上的Rx和Tx引脚与跳线相连,因此无论发送什么都应立即接收.
I have a simple program written in C which uses termios to send a basic string to the Raspberry Pi UART and attempts to read and output the response. The Rx and Tx pins on the Raspberry Pi are connected with a jumper so whatever is sent should be immediately received.
尽管程序输出成功为选定的字符串("Hello")发送和接收了5个字符,但尝试打印缓冲区的内容只会产生一两个垃圾字符.
Despite the program outputting that it successfully sent and received 5 characters for the chosen string ('Hello'), trying to print the contents of the buffer just produces one or two garbage characters.
程序:
#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波特以下的任何东西都将导致收不到任何东西.
I can't see any major problem with the code myself, but I might be wrong. I can successfully send and receive characters using PuTTY connected with the same settings, so it can't really be a hardware problem. Although I haven't tried it in PuTTY, trying to connect with anything less than 115200 baud with this program will result in nothing being received.
我要去哪里错了?
推荐答案
int wcount = write(fd, &str, strlen(str));
int rcount = read(fd, &buffer, sizeof(buffer));
在这些行中,buffer/str已经是指针.您正在将指针传递给指针.
In these lines, buffer/str are already pointers. You are passing a pointer to a pointer.
行应为:
int wcount = write(fd, str, strlen(str));
int rcount = read(fd, buffer, sizeof(buffer));
这篇关于使用termios的C语言中的Raspberry Pi UART程序接收垃圾(Rx和Tx直接连接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!