当前位置: 技术问答>linux和unix
linux下串口读写问题 read 一次读不全
来源: 互联网 发布时间:2016-02-04
本文导语: 我要在本机(linux)串口上进行读写,一开始时发送接收都正常,但是我用windos下的“串口调试助手”发送给我的程序时必须要加上回车换行,否则read函数不返回,后来google了一下,又添加了2条语句设置串口(代码在下...
我要在本机(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 0 )
{
tv_timeout.tv_sec = timeout; //time out : unit sec
tv_timeout.tv_usec = 0;
fs_sel = select( m_hCom+1, &fs_read, NULL, NULL, &tv_timeout);
}
else//死等
{
fs_sel = select( m_hCom+1, &fs_read, NULL, NULL, NULL );
}
if(fs_sel)
{
readlen = read(m_hCom, data, datalen);
return readlen;
}
else
{
return(-1);
}
return readlen;
}
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 0 )
{
tv_timeout.tv_sec = timeout; //time out : unit sec
tv_timeout.tv_usec = 0;
fs_sel = select( m_hCom+1, &fs_read, NULL, NULL, &tv_timeout);
}
else//死等
{
fs_sel = select( m_hCom+1, &fs_read, NULL, NULL, NULL );
}
if(fs_sel)
{
readlen = read(m_hCom, data, datalen);
return readlen;
}
else
{
return(-1);
}
return readlen;
}