日期:2014-05-18 浏览次数:20934 次
while (true) { int recvlen = comm.Read(buffer, offset, count); // count ,不知道哪里给改变成 负值了
private void button6_Click(object sender, EventArgs e) { int n; byte[] sendbyte = { 0xF0, 0x03, 0x7E, 0x01, 0x8E, 0x70, 0x01, 0x17, 0x01, 0x06, 0x00, 0x00, 0xFF, 0xFF, 0x01, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x42, 0x70, 0x01, 0x17, 0x01, 0x06, 0x00, 0x00, 0xFF, 0xFF, 0x01, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x76,0xF0, 0x03, 0x7E, 0x03, 0x8B}; ThreadPool.QueueUserWorkItem(recv2, comm); while (true) { comm.Write(sendbyte, 0, sendbyte.Length); n = sendbyte.Length; send_count += n;//累加发送字节数 labelSendCount.Text = "Send:" + send_count.ToString();//更新界面 } }
static void recv2(object obj) { SerialPort comm = (SerialPort)obj; byte[] buffer = new byte[256]; int offset = 0; int count =2; while (true) { int recvlen = comm.Read(buffer, offset, count); if (recvlen != count) { offset += recvlen; count -= recvlen; continue; } if (offset < 2) { if (buffer[0] == 0xf0) { offset = 2; count = buffer[1]; continue; } if (buffer[0] == 0x70) { offset = 2; count = 1; continue; } } if (offset < 3) { offset = 3; if (buffer[0] == 0x70) { count = buffer[2] - 3; } else { count = buffer[1] - 3; } continue; } int len = 0; if (buffer[0] == 0xf0) len = 2 + buffer[1]; else len = buffer[2]; //显示buffer从0到len的内容 offset = 0; count = 2; } }