通过阻塞/轮询向ttyUSB串口设备收发AT命令

通过阻塞/轮询向ttyUSB串口设备收发AT命令

一、概述

本文总结了分别使用阻塞、轮询两种方式,向ttyUSB串口设备(4G模块)发送AT命令,并读取AT命令返回的结果。

二、read阻塞方式

首先需要以阻塞方式打开ttyUSB串口设备,即open第三个参数中不包括NDELAY(NOBLOCK)参数

fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY);
    /* O_RDWR   - Read/Write access to serial port           */
    /* O_NOCTTY - No terminal will control the process       */
    /* O_NDELAY - Open in noblocking mode,read will not wait */ 
    if(fd == -1)						/* Error Checking */
    {
    
    
        printf("\n  Error! in opening ttyUSB0");
        return -1;
    }
    else
    {
    
    
        printf("\n  Success! in opening ttyUSB0");
 
    }

然后配置阻塞参数:c_cc[VMIN]>N和c_cc[VTIME]=0,即内核缓冲区至少有N个数据read函数才会读取AT命令返回值,否则将read函数一直阻塞。

while(1)
{
    
    
	printf("\n in blocking mode");	
	bytes_read = read(fd, &read_buffer, 32);     // receive AT return
	printf("\n  %s read bytes is %d", read_buffer,bytes_read);
	memset(read_buffer, 0, sizeof(read_buffer));
}

三、read轮询方式

配置c_cc[VMIN]=0和c_cc[VTIME]=0,即可配置为轮询方式,缓冲区没有AT命令应答数据,read函数也会返回,因此需要通过返回值判断是否有AT命令应答数据。

while(1)
{
    
    
   printf("\n in polling mode");        
   bytes_read = read(fd, &read_buffer, 32);     // receive AT return
   if(bytes_read != 0)
   {
    
    
     printf("\n  %s read bytes is %d", read_buffer,bytes_read);
	 memset(read_buffer, 0, sizeof(read_buffer));
   }
}

四、总结

1、缓冲区的概念:在通过open打开串口通信设备时,在应用层和内核层都将开辟串口收发数据缓冲区,串口的发送和接收数据都将经过缓冲区存储,因此在发送AT命令后的应答数据,可以在内核数据缓冲区中读取,不用在一个收发进程中读取不到AT返回数据。
2、建议使用阻塞方式,降低CPU占用率。
3、注意:要以阻塞方式open串口设备。
4、注意:配置c_cc[VMIN]>N时,读到N个数据才会返回,或者收到一个信号的时候也会返回。

猜你喜欢

转载自blog.csdn.net/weixin_39789553/article/details/115217149