cmxzlove 发表于 2015-11-22 19:50:38

串口接收指定长度数据问题 求助!


小弟我最近做串口接收数据的函数,接收数据格式"+PID,5,2:AD"(引号内为传输数据),+PID是抬头,5为标号,2为数据长度,冒号后面为数据,即为数据长度为10时,冒号后面有十个字节的数据,现在是数据长度为50左右时,接受到的数据正常,数据长度上了60后,就接收不完整了!我是机械出身,还请给位大侠不吝赐教!谢谢!

比如发送串口数据:+PID,5,50:##QWERT11111111112222222211111111112221111111111**arduino接受后串口打印:##QWERT11111111112222222211111111112221111111111**


而发送:+PID,5,60:##QWERT111111111122221111111111222211111111112221111111111**,串口打印的是:##QWERT1111111111222211111111112222111111111122211111                     后面有一截空白

下面是我测试的代码!请指教!
#define SERIAL_TX_BUFFER_SIZE 256
#define SERIAL_RX_BUFFER_SIZE 256
String re="";
void setup()
{
Serial.begin(250000);
}

int scan_serial(String *s)
{
int flag=0;
String temp="";
String dd="";
char a;
while(Serial.available()>0)
{
    a=Serial.read();
    if(a=='+')
    {
      while(Serial.available()>0)
      {
      temp+=char(Serial.read());
      if(temp==':')
      {
          int i=temp.indexOf(',',0);
          i=temp.indexOf(',',i+1);
          int m=(temp.substring(i+1,temp.length()-1)).toInt();
          Serial.println(m);
          temp="";
          for(int l=0;l<m;)
          {
            dd+=char(Serial.read());
            if(dd.length()>0)
            {
            temp+=dd;
            dd="";
            l++;
            }
            delay(2);
          }
          Serial.println(temp);
          *s=temp;
          Serial.flush();
          return 1;
      }      
      }
    }
}
}
void loop()
{
delay(100);
if(scan_serial(&re)==1)
{
    Serial.println(re);
    re="";
}
}

zoologist 发表于 2015-11-22 22:23:01

不知道是不是和arduino 串口buffer长度有关系,接收buffer只有 64

cmxzlove 发表于 2015-11-23 12:28:47

zoologist 发表于 2015-11-22 22:23 static/image/common/back.gif
不知道是不是和arduino 串口buffer长度有关系,接收buffer只有 64

确实!我将缓存大小改到512发送280多个字节的数据能正常接收了!谢谢!
页: [1]
查看完整版本: 串口接收指定长度数据问题 求助!