如果串口的字节数多,那么每间隔一会BytesToRead的结果便会不同(每次都会增加)。用DataReceived事件也是这样。于是
byte inbuffer =new byte[serialPort.BytesToRead];
serialPort.Read(inbuffer, 0, serialPort.BytesToRead);
便不能把数据全部读取,只能读取一部分。后来又加上循环,改成:
   byte inbuffer =new byte[serialPort.BytesToRead];
   Thread.Sleep(200);
   while (inbuffer.Length != serialPort.BytesToRead)
   {
         Thread.Sleep(200);
         inbuffer = new byte[serialPort.BytesToRead];
   } 
   serialPort.Read(inbuffer, 0, serialPort.BytesToRead);可事实上根本就不起作用。因为循环体根本就没执行。
不知如何解决 请教高人。。

解决方案 »

  1.   

    串口是流设备,在linux下叫字符设备。
    意思是数据是连续产生,顺序存取的。你如何能读完呢?如果串口数据协议简单,你可以设置Serialport控件的NewLine属性,例如常见的回车换行结尾,就设置NewLine="\r\n";然后再你的时间里写:ReadLine,应该就能读到你要的数据。反之,一般的过程是读取->缓存->判定数据完整性->数据校验->数据分析->通知界面或丢弃。
      

  2.   


      byte[] inbuffer =new byte[1024];
      string instr;
      while (serialPort.BytesToRead > 0)
      {
          int len = Min(1024, serialPort.BytesToRead);
          serialPort.Read(inbuffer, 0, len);
          //处理inbuffer
          instr += ASCII.GetString(inbuffer, 0, len);
          //处理字符串
      }
     Com口是连续读的,不会有结束的时候,一般有接收事件触发时,连续把串口的数据全部读取,然后再做处理,处理完成后看具体情况剩下的数据是丢弃还是保留到下一次接着处理。
      

  3.   

    不知道你的方法为什么不行,我一般都是这样读的。先设置读串口超时时间为20毫秒(自己看情况设置),然后一个字节一个字节地读数据,一旦超时表示读串口完成。//读串口超时时间为20毫秒
    serialPort.ReadTimeout = 20;
    int len = 0;
    int maxLen=1000;
    byte[] data = new byte[maxLen];
    try
    {
        //读串口数据
         while (true)
        {
             data[len] = (byte)serialPort.ReadByte();
             len++;
        }
    }
    catch { }
                    
      

  4.   

    int bytecount = serialPort1.BytesToRead;
    byte[] byteBar = new byte[bytecount];
    serialPort1.Read(byteBar, 0, bytecount);
    for (int i = 0; i < byteBar.Length; i++)
    {
      if (byteBar[i].ToString() != "13")
      {
    ls_ReceviBAR += (char)byteBar[i];
      }  
    }