日期:2014-05-18 浏览次数:20901 次
this.txGet.AppendText(str+"\r\n");
int n = comm.BytesToRead; byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据 bool data_1_catched = false; string str = ""; received_count += n;//增加接收计数 temp_Counter += n; comm.Read(buf, 0, n);//读取缓冲数据 if (n > 0) { Array.ConstrainedCopy(buf, 0, binary_data_1, temp_Counter - n, n); if (temp_Counter - n > 0) data_1_catched = true; //正确分析一条数据,从缓存中移除数据。 // Array.Clear(buf, 0, buf.Length); } if (data_1_catched) { this.Invoke((EventHandler)(delegate { for (int i = 0; i < temp_Counter; i++) { str += binary_data_1[i].ToString("X2"); } this.txGet.AppendText(str+"\r\n"); temp_Counter = 0; data_1_catched = false; Array.Clear(binary_data_1, 0, binary_data_1.Length); //修改接收计数 labelGetCount.Text = "Get:" + received_count.ToString(); }));
int isread = 0; byte[] buffer = new byte[64];//长度根据你的协议需要定义 void comm_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (Interlocked.CompareExchange(ref isread, 1, 0) != 0) return; while (true) { try { int recvlen = comm.Read(buffer, 0, buffer.Length); //程序对接收到的buffer的处理过程,实际接收长度为recvlen } catch { break; } } Interlocked.CompareExchange(ref isread, 0, 1); }