兄弟们啊,搞一个串口通讯,老出现操作已超时提示。一下是代码//初始化串口
SerialPort TestSerialPort = new SerialPort();
string serialportpar = "com3,57600,0,8,1";
string[] comPortParams = comParams.Split(new char[] { ',' }, 5);
TestSerialPort .PortName = comPortParams[0];
TestSerialPort .BaudRate = Convert.ToInt32(comPortParams[1]);
TestSerialPort .Parity = Parity.None;
TestSerialPort .DataBits = Convert.ToInt32(comPortParams[3]);
TestSerialPort .ReadTimeout = 500;
TestSerialPort .WriteTimeout = 500;
TestSerialPort .ReadBufferSize = 2000;
TestSerialPort .WriteBufferSize = 2000;  //发送给串口的初始byte数组
byte[] firstsendBuf ={ 0x7E,0x0A,0x01, 0xA3, 0x00, 0x00, 0x7E };
string aa = "";
//开启端口
TestSerialPort.Open();
Thread.Sleep(100);
try
{
    TestSerialPort.Write(firstsendBuf, 0, firstsendBuf.Length);
}
catch (Exception ex)
{
     MessageBox.Show(ex.Message);
                   
}
Thread.Sleep(100);
//接收缓存。这里只接收一个byte
byte[] receiveBuf =new byte[1];
Thread.Sleep(100);
while (true)
{
    if (int.Parse(receiveBuf[0].ToString()) > 0)
         break;
    else
         TestSerialPort.Read(receiveBuf, 0, 1);}
就是红色部分报错,请做过串口通信的兄弟们帮个忙

解决方案 »

  1.   

    TestSerialPort.Read(receiveBuf, 0, 1);
    狂汗啊,就是这句话报错!提示操作已超时,我代码中有错误么各位?
      

  2.   

    用TestSerialPort.ReadExisting会不会报错?先不说读来的是不是你要的格式,先排除错误。
      

  3.   

    主要是看COM3是不是正常,和它的波特率
      

  4.   

    改写到SerialPort的DataRecive事件里面吧,你这样读,COM口一直没数据,自然会超时了。
      

  5.   

    那你修改为这样试试while (true)
    {
    if(TestSerialPort.BytesToRead==0)
    {
    Application.DoEvents();
    continue;
    }
        if (int.Parse(receiveBuf[0].ToString()) > 0)
    {
             break;
    }
        else
        {
    receiveBuf = (byte)TestSerialPort.ReadByte();
    }
    }
      

  6.   

    我刚刚用串口助手试了下,可以从串口收到正确数据
    但是用逍遥的码,一直在while循环里,意思就是读不到串口的数据,
    另外,波特率是57600没错,别的参数也都是正确的,我这个代码是别人很早前做的,发和读数据都没问题,可现在要更改下读数据方式,所以我必须重写,
      

  7.   

    是不是注册了DataReceived事件?那可能你这里一直没数据是因为事件中先读空了串口。你不要注册事件,避免竞争读。
      

  8.   

                    int tickCount = System.Environment.TickCount;
                    while ((System.Environment.TickCount - tickCount) < 1000)
                    {
                        System.Threading.Thread.Sleep(30);
                        if (comPort.BytesToRead > 0)
                        {
                            while (comPort.BytesToRead > 0)
                            {
                                System.Threading.Thread.Sleep(30);
                                byte[] RcvBytes = new byte[comPort.BytesToRead];
                                comPort.Read(RcvBytes, 0, RcvBytes.Length);
                                System.Threading.Thread.Sleep(50);
                            }
                            break;
                        }
                    }试下这段代码
      

  9.   

    不行的话 试试DataReceived事件