Linux-从C中的串行端口读取错误(资源暂时不可用)
我正在尝试使用usb/rs232转换器从串行端口读取一些数据。我从atmega发送数据,并在minicom中正确接收。但是,试图在我的程序中读取某个内容最终导致错误资源暂时不可用。我知道这是O_NDELAY造成的,但删除它会给我带来大量的空消息,这也不好 实际上,我想要实现的是一个程序,它每秒钟都会向atmega发送一些字符,并等待响应。根据响应,它将执行不同的操作。此外,在几次未应答的传输后,程序将指示通信错误 但现在我希望至少能收到一些合适的东西 这是我的密码:Linux-从C中的串行端口读取错误(资源暂时不可用),c,linux,serial-port,C,Linux,Serial Port,我正在尝试使用usb/rs232转换器从串行端口读取一些数据。我从atmega发送数据,并在minicom中正确接收。但是,试图在我的程序中读取某个内容最终导致错误资源暂时不可用。我知道这是O_NDELAY造成的,但删除它会给我带来大量的空消息,这也不好 实际上,我想要实现的是一个程序,它每秒钟都会向atmega发送一些字符,并等待响应。根据响应,它将执行不同的操作。此外,在几次未应答的传输后,程序将指示通信错误 但现在我希望至少能收到一些合适的东西 这是我的密码: #include <u
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
int fd; //file descriptor
int bytes; // bytes to read
int PortOpen(void)
{
fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NDELAY);
if(fd < 0)
{
//opening error
printf("Port opening error\r\n");
}
else
{
printf("Port opened\r\n");
//port config
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag |= CLOCAL;
options.c_cflag |= CREAD;
options.c_cflag &= ~CRTSCTS;
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 5;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
//Modifying c_iflag by bitwise OR and AND
options.c_iflag &= ~(ICRNL | INLCR | IGNCR | IUCLC);
options.c_iflag &= ~(IXON | IXOFF | IXANY);
//Modifying c_oflag by bitwise OR and AND
options.c_oflag &= ~OPOST;
tcflush(fd, TCIFLUSH);
//Setting the new settings for the port immediately
tcsetattr(fd, TCSANOW, &options);
}
return 1;
}
int PortRead(void)
{
int n = 0, spot = 0;
char buf = '\0';
/* Whole response*/
char response[1024];
memset(response, '\0', sizeof response);
do {
n = read( fd, &buf, 1 );
sprintf( &response[spot], "%c", buf );
spot += n;
} while( buf != '\r' && n > 0);
if (n < 0)
{
printf("Error reading: %s\r\n",strerror(errno));
}
else if (n == 0)
{
printf("Read nothing!\r\n");
}
else
{
printf("Response: %s", response);
}
return 1;
}
int main(void)
{
PortOpen();
int j;
for(j=0; j<100; j++) //just testing
{
PortRead();
}
return 0;
}
当未设置为O_NDELAY/O_NONBLOCK时,读取块不应该被设置为O_NDELAY/O_NONBLOCK吗?不管怎样,如果我是你,我会查看poll或select;,不需要memset。强烈建议使用select control a循环,这样读取就不会被调用,除非至少要读取1个字符。注意:没有防止字符响应的缓冲区溢出的保护[1024];在PortRead中。当未设置为O_NDELAY/O_NONBLOCK时,读取不应该阻塞吗?不管怎样,如果我是你,我会查看poll或select;,不需要memset。强烈建议使用select control a循环,这样读取就不会被调用,除非至少要读取1个字符。注意:没有防止字符响应的缓冲区溢出的保护[1024];在PortRead。