【发布时间】:2014-12-15 22:24:00
【问题描述】:
我在Linux上写一个串口数据传输的程序,但是发现每次发送方打开端口,接收方都会得到一个额外的空字节'\x00'。
这里是发件人的代码:
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
int main(int argc, char* argv[]) {
int fd_com_ = open("/dev/ttyAM0", O_RDWR | O_NOCTTY | O_NONBLOCK);
struct termios attrs_;
attrs_.c_iflag = IGNBRK;
attrs_.c_oflag = 0;
attrs_.c_cflag = (CLOCAL | CREAD);
attrs_.c_cflag |= CS8;
attrs_.c_lflag = 0;
attrs_.c_cc[VMIN] = 0;
attrs_.c_cc[VTIME] = 0;
cfsetspeed(&attrs_, B115200);
tcsetattr(fd_com_, TCSANOW, &attrs_);
const char *s = "abcd";
write(fd_com_, s, 4);
sleep(1);
write(fd_com_, s, 4);
sleep(1);
close(fd_com_);
fd_com_ = open("/dev/ttyAM0", O_RDWR | O_NOCTTY | O_NONBLOCK);
write(fd_com_, s, 4);
return 0;
}
接收器具有相同的配置,但接收到"\x00abcdabcd\x00abcd"。如何解决这个问题,以便接收者可以得到"abcdabcdabcd"?
更新:
接收方代码:
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
int main(int argc, char* argv[]) {
int fd_com_ = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NONBLOCK);
struct termios attrs_;
attrs_.c_iflag = IGNBRK;
attrs_.c_oflag = 0;
attrs_.c_cflag = (CLOCAL | CREAD);
attrs_.c_cflag |= CS8;
attrs_.c_lflag = 0;
attrs_.c_cc[VMIN] = 0;
attrs_.c_cc[VTIME] = 0;
cfsetspeed(&attrs_, B115200);
tcsetattr(fd_com_, TCSANOW, &attrs_);
char buf[100];
ssize_t sz;
while(1) {
sz = read(fd_com_, buf, 100);
if (sz > 0) {
for (ssize_t i=0; i<sz; i++) {
printf("%02hhx\n", buf[i]);
}
}
sleep(1);
}
return 0;
}
【问题讨论】:
-
如果只打开和关闭端口,是否也会收到空字节?可以发一下接收代码吗?
-
@iharob 是的,在评论最后一个
write之后,接收者仍然得到一个空字节。我已经发布了接收者的代码。 -
你能描述一下串口设置,什么连接在哪里。
-
@iharob 发送器在 ARM 板上运行,接收器在我的 PC 上。由于我的 PC 上没有串行端口,因此使用了 USB 串行设备。
-
对不起,我不知道如何帮助你。它可能与您的特定设置有关,因为
write函数正在发送正确的数据,并且代码对我来说看起来不错,所以不知道发生了什么。我多希望我能帮忙。我以前使用过串行端口,但从未遇到过这种行为。
标签: c linux serial-port