我想實現的是上位機發送數據,然後接收數據,然後上位機處理數據,再繼續發送數據一直循環到結束。
目前的問題就是,我通過以下代碼實現的是在循環調用測試函數,循環運行完了以後,才開始讀取數據
public Form1()
{
InitializeComponent();
serialPort1.DataReceived += serialPort1_DataReceived;
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.Invoke(new EventHandler(Read));
}
private void Read(object s, EventArgs e)
{
int n = serialPort1.BytesToRead;
byte[] buf = new byte[n];
serialPort1.Read(buf, 0, n);
data_catched=true;
}
public bool test_CA()
{//測試CA
//定義附加信息
Byte[] test_CA_add = new Byte[1] { 0x00 };
//發送命令幀
Write(test_cmd_CA, test_CA_add);//發送數據函數測試無誤,並在發送完後立刻有數據返回
byte test_CA_data;
//時延等待接收數據
for (int i = 0; !data_catched && i < 300; i++)
{
Thread.Sleep(10);
}
if (!data_catched)
{
//處理數據
}
data_catched=false;
}
for (int i = 0; !data_catched && i < 300; i++)
{
Thread.Sleep(10);
Application.DoEvents();
}