【发布时间】:2011-11-08 16:37:35
【问题描述】:
我正在编写一个与AVR MCU通信的小程序,在PC端我使用posix write()和read()来访问串口,我连接了串口的RX和TX引脚来测试它是否可以正常发送和接收数据,理论上发送出去的所有东西在接收缓冲区中应该是完全一样的,当发送的消息很短并且发送频率很低时,read()返回的消息和发送出去的一样,但是当消息变得更长并且发送更频繁时, read() 返回错误的数据,字符似乎顺序错误,我的猜测是 read() 或 write() 不是块模式,所以当旧传输没有'还没有完成,新的传输(write()?)到达,中断旧的传输并更改了 TX 缓冲区。
我是 Linux 编程的新手,请任何人帮助我,这让我很生气...... 非常感谢任何帮助。
编辑:我在 write() 手册页中注意到: write() 的成功返回并不能保证数据已提交到磁盘。事实上,在一些有缺陷的实现中,它甚至不能保证已成功为数据保留空间。唯一可以确定的方法是在完成所有数据的写入后调用 fsync(2)。
我尝试了 fsync() 函数,仍然得到同样的错误结果。
代码如下:
#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("%s\n", in);
}
return 0;
}
埃里克
【问题讨论】:
标签: linux serial-port posix