我正在尝试通过串口发送一些chars
。问题是,如果我发送A
(ASCII 65
),我会收到其他内容(ASCII 225
)。我发送的任何字母或字符串都会收到其他内容。
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
int open_port(void)
{
int port;
port = open("/dev/ttySAC3", O_RDWR | O_NOCTTY | O_NDELAY);
if (port == -1){
perror("open_port: Unable to open /dev/ttySAC3 - ");
}else{
fcntl(port, F_SETFL, 0);
}
return (port);
}
int main()
{
int port,n;
char str = 'A';
struct termios specs;
port = open_port();
tcgetattr(port, &specs);
specs.c_cflag = (CLOCAL | CREAD );
specs.c_oflag = (OPOST | CR3| CS8);
cfsetospeed(&specs,B9600);
tcsetattr(port,TCSANOW,&specs);
n = write(port, &str, 1);
if (n<0) {
printf("\nError");
}
close(port);
return(0);
}
我使用示波器进行了测量,这是离开设备的数据,所以这不是我电脑上的读数问题。
我在网上搜索了最近2天,无法弄清楚我做错了什么。一些帮助将不胜感激。
答案 0 :(得分:2)
如果您获得“'B'
”的226,那么我会说uP发送'b'
并且使用 7 数据位和使用奇偶校验。
来自 N Alex 的评论我得出结论:
他可以简单地为termios结构添加适当的初始化:
struct termios specs = {0};
答案 1 :(得分:1)
波特率是一个参数,还有数据位数,停止位,奇偶校验和流量控制(RTS / CTS,无等)。如果两侧的硬件都支持这些参数,则两侧的参数必须相同。如果是这种情况,则电缆Rx,Tx必须将Rx(A侧)连接到Tx(B侧),将Tx(A侧)连接到Rx(B侧)。
如果我们忽略干扰和流量控制引脚的接地和电网,这是最低要求。
下一个考虑因素是距离。由于附近静电发射器(手机,电机等)的干扰,RS232不能在标准电缆上走得太远
最后,最难的是RS232没有纠错。如果在传输过程中某些位发生了变化,那么另一方只能检查数据包是否正确到达非常低的程度,但它无法纠正。为此,您需要双方都有纠错协议,或者至少需要一个ACK / NAK机制。
希望这有帮助。