【发布时间】:2016-01-28 10:45:05
【问题描述】:
我想使用 RS232 端口与我的 PC 通信。我可以使用 write() 函数打开“/dev/ttyS0”并写入数据,但使用 read() 无法从“dev/ttyS0”读取正确的数据>。 read() 函数读取了不需要的数据。请告诉我如何解决这个问题?
我的程序代码在这里:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
int main()
{
int n = 0, fd = 0, bytes = 0;
char buffer[10];
struct termios term;
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open");
return;
}
else
{
fcntl(fd, F_SETFL, 0);
perror("Port");
}
tcgetattr(fd, &term);
cfsetispeed(&term, B115200);
cfsetospeed(&term, B115200);
term.c_cflag |= (CLOCAL | CREAD);
term.c_cflag &= ~PARENB;
term.c_cflag &= ~CSTOPB;
term.c_cflag &= ~CSIZE;
term.c_cflag |= CS8;
term.c_cflag &= ~CRTSCTS;
term.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
term.c_iflag &= ~(IXON | IXOFF | IXANY);
term.c_oflag &= ~OPOST;
term.c_cc[VMIN] = 0;
term.c_cc[VTIME] = 10;
tcsetattr(fd, TCSANOW, &term);
printf("Enter the string...\n");
scanf("%s", buffer);
write(fd, buffer, sizeof(buffer));
perror("write");
// fcntl(fd, F_SETFL, FNDELAY);
sleep(1);
bytes = read(fd, buffer, sizeof(buffer));
perror("read");
buffer[bytes] = '\0';
printf("Bytes : %d\n", bytes);
printf("%s\n", buffer);
memset(buffer, '\0', 10);
}
【问题讨论】:
-
请举例说明您正在阅读什么数据以及您期望什么
-
为什么要使用非阻塞 IO?你知道这是什么效果吗?
-
例如“Hello world”读写垃圾数据
-
@FUZxxl:好点。也许
fd在调用tcgetattr时还没有准备好(所以它可能只是返回-EAGAIN。代码不会检查任何错误,所以我建议使用strace来查看进行了哪些系统调用,以及它们的返回值是什么。另外,请使用已知良好的终端模拟器,如minicom以确保一切正常。 -
@PeterCordes 库函数永远不会清除
errno。这是 POSIX 规则。
标签: c linux serial-port