日期:2014-05-16  浏览次数:20898 次

linux下串口读写问题 read 一次读不全
我要在本机(linux)串口上进行读写,一开始时发送接收都正常,但是我用windos下的“串口调试助手”发送给我的程序时必须要加上回车换行,否则read函数不返回,后来google了一下,又添加了2条语句设置串口(代码在下面说明),现在收数据可以不用加回车换行了,但是每次read返回的数据都不完整,比如我发了20个字符,read先是读取了8个字符到缓冲区,然后又读取剩下的字符。有没有什么办法可以一次读取全部的,或者可以判断数据还没有收完,接着read,直到结束.

int   speed_arr[]   =   {   B38400,   B19200,   B9600,   B4800,   B2400,   B1200,   B300,
        B38400,   B19200,   B9600,   B4800,   B2400,   B1200,   B300,};
int   name_arr[]   =   {38400,     19200,     9600,     4800,     2400,     1200,     300,   38400,
        19200,     9600,   4800,   2400,   1200,     300,};

/**
*@brief     Set   Serial   Port   BitRate
*@param     fd           Type   :   int   The   File   Description   of   Serial   Port
*@param     speed     Type   :   int     Serial   Speed
*@return     void
*/
void   set_speed(int   fd,   int   speed)
{
        int       i;  
        int       status;  
        struct   termios       Opt;
        tcgetattr(fd,   &Opt);
        for(   i=0;   i   <   (sizeof(speed_arr)   /   sizeof(int));   i++   )
        {
                if   (speed   ==   name_arr[i])
                {
                        tcflush(fd,   TCIOFLUSH);          
                        cfsetispeed(&Opt,   speed_arr[i]);    
                        cfsetospeed(&Opt,   speed_arr[i]);      
                        status   =   tcsetattr(fd,   TCSANOW,   &Opt);    
                        if   (status   !=   0)
                        {
                                perror( "tcsetattr   fd ");    
                                return;          
                        }
                        tcflush(fd,TCIOFLUSH);      
                }
        }
}

/**
*@brief       Set   Serial   Port   Databits,   Stopbits   and   Parity.
*@param     fd           Typ