Linux RS232读取错误:资源暂时可用

时间:2016-10-17 10:01:51

标签: linux serial-port

我是串口编程的初学者。我想要做的是在获得响应之后轮询设备,然后做一些事情。现在我无法从端口读取,但写得正确。

我在VM上使用Ubuntu 14.04,并使用虚拟串口进行测试。但即使连接我的设备,问题仍然存在。我已经安装了端口监控程序,如下图所示:

enter image description here

以下是我的代码:

void *gp_def(void *arg);
int fd;
pthread_mutex_t mu;

int main(void){

int c=0, res=0;
struct termios oldtio, newtio;
char buf[256];

printf("Start...\n");
fd = open("/dev/ttyS0", O_RDWR|O_NOCTTY|O_NDELAY);
if (fd < 0)
{
    perror("error!\n");
    exit(1);
}
printf("Open...\n");
tcgetattr(fd, &oldtio);
bzero(&newtio, sizeof(newtio));
newtio.c_cflag = BAUDRATE|CS8|CLOCAL|CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = ICANON;

tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &newtio);

printf("Reading...\n");
int i=0;

pthread_t gp;
int res0,res1;
res0=pthread_create(&gp,NULL,gp_def,NULL);
res1=pthread_mutex_init(&mu,NULL);
if (res0!= 0)
{
    printf("gpThread() failed\n");
    exit(EXIT_FAILURE);
}
if (res1!= 0)
{
    printf("mutex initial failed\n");
    exit(EXIT_FAILURE);
}

for(i=0; i<1000; i++)
{

    char data[5]= {0x80,0x01,0x01,0x51,0x08}; //lock

    pthread_mutex_lock(&mu);

    write(fd,data,5);
    pthread_mutex_unlock(&mu);
    sleep(2);
    res = read(fd, buf, sizeof(buf));
    perror("res");
    buf[res]=0;
    printf("res=%d buf=%s\n", res, buf);

    if (buf[0] == '@') break;
    //printf("here\n");

}


printf("Close...\n");
close(fd);

return 0;
}

void *gp_def(void *arg){
while(1)
{
    char data[2]= {0x80,0x81}; //loc
    pthread_mutex_lock(&mu);
    write(fd,data,2);
    pthread_mutex_unlock(&mu);
    sleep(1);

}


}

更新

我尝试过不使用非阻塞模式打开端口,并使用select()来 监控fd的状态。

int isready(int fd)
{
int rc;
fd_set fds;
struct timeval tv;

FD_ZERO(&fds);
FD_SET(fd,&fds);
tv.tv_sec = tv.tv_usec = 0;
rc = select(fd+1,&fds,NULL,NULL,&tv);

if(rc < 0)
    return 10;//error
   //return FD_ISSET(fd,&fds) ? 1 : 0;
else if(rc>0){
    return 100;
}
else
    return -100;
}

在main()

while(1){
    ....
    if(isready(fd)!=100)
        printf("not ready\n");
    else{
        res=read(fd,buf,sizeof(buf));
    }
    ....
}

我仍然无法读取数据。选择始终返回-100

0 个答案:

没有答案