微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux串口读取错误的数据

我正在写一个小程序来与AVR MCU进行通信,在PC端我使用了posix write()和read()来访问串口,我连接了串口的RX和TX引脚来testing它是否能够正确的发送和接收数据,在理论上,发送出来的内容应该在接收缓冲区中完全相同,发送的消息较短,发送频率较低时,read()返回与发送消息相同的消息,但当消息()返回错误的数据,字符似乎是错误的顺序,我的猜测是read()或write()不是在块模式,所以当旧的传输尚未完成,新的传输(write()?)到达,中断旧的传输并更改TX缓冲区。

我是一个在Linux编程新手,请有人帮助我,这是杀了我…任何帮助,非常感谢。

编辑:我注意到在写()手册页:从write()的成功返回不保证数据已提交到磁盘。 事实上,在一些错误的实现中,它甚至不保证空间已经成功地被保留用于数据。 唯一可以确定的方法是在写完所有数据后调用fsync(2)。

我尝试了fsync()函数,仍然得到相同的错误结果。

串口ReadFile读取0个字节并返回true

Linux串口读取后修改一个字符的Linux termios()

用Win32 Api在C程序中进行串行连接

通过串口发送文件

与Windows XP / win32串行通信的基本示例

这里是代码

#include <stdio.h> #include <stdio.h> /* Standard input/output deFinitions */ #include <string.h> /* String function deFinitions */ #include <unistd.h> /* UNIX standard function deFinitions */ #include <fcntl.h> /* File control deFinitions */ #include <errno.h> /* Error number deFinitions */ #include <termios.h> /* POSIX terminal control deFinitions */ int main(void) { int fd; // fd = open("/dev/tty.usbmodem1a21",O_RDWR | O_NOCTTY | O_NDELAY); fd = open("/dev/tty.usbmodem1a21",O_RDWR | O_NOCTTY); if (fd == -1) { //Could not open the port. perror("open_port: Unable to open port "); } else fcntl(fd,F_SETFL,0); char s[] = "Hello,this is a test of the serial port access"; int cnt; unsigned char in[100]; for(cnt=0; cnt<10; cnt++) { int n = write(fd,s,sizeof(s)); if (n < 0) fputs("write() Failed!n",stderr); usleep(50000); // works fine with delay read(fd,in,100); printf("%sn",in); } return 0; }

埃里克

我想从COM端口连续接收数据,同时要写入文件

使用boost.asio是否可以使用标记和空格?

如何获得有关Windows中的串行(COM)端口的特定信息?

在C中写入串行适配器

读取没有高cpu使用率的串行数据

首先使用read()的返回值。 记住:read 不会产生nul结尾的字符串。

n=read(fd,100); printf("%*.*sn",n,in);

(1)总是检查返回码。 (2)如果你尝试printf一个没有被null终止的字符串,你将最终打印内存中的任何垃圾(或更糟)。

我的猜测是,你真正的问题是读/写不能保证写你指定的字节数。 他们实际读/写的数字在返回代码中。 因此,当fd缓冲区填满时,您可能会写入1个字节,然后尝试打印该1个字节的非空字符串及其后的所有内容

尝试这样的事情,看看事情是否改变。

int cnt; unsigned char in[100]; for(cnt=0; cnt<10; cnt++) { int n = write(fd,sizeof(s)); if (n < 0) { perror("write"); exit(EXIT_FAILURE); } n = read(fd,100); if (n < 0) { perror("read"); exit(EXIT_FAILURE); } in[n] = ''; printf("%sn",in); }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐