sp.DiscardInBuffer();//清除接受緩存 sp.WriteLine("AT+CMMS=3");//發命令 int tick = Environment.TickCount;//記錄當前時間戳 int timeout = 2000;//你這個自己定,我假設2秒延遲等待應答,超過則提示超時無應答。 bool ack_found = false;//標誌是否收到應答 StringBuilder buf = new StringBuilder();//定義緩存 while(Environment.TickCount - tick < timeout && !ack_found)//如果沒收到應答或尚未超時,則循環 { buf.Append(sp.ReadExisting());//將當前串口數據記錄進緩存 //ack_found表示是否收到應答,沒收到的話再繼續循環就可以了。 ack_found = buf.ToString().IndexOf("OK") != -1;//假設應答為OK,檢查收到數據中是否包含應答。 Application.DoEvents();//處理消息,避免界面卡死 } if(!ack_found) { MessageBox.Show("step 1 error response. Try later."); return; }