logo资料库

c# 串口通讯如何多次重复发送一帧数据,并且保证发送和回复每一帧数据的顺序正.docx

第1页 / 共5页
第2页 / 共5页
第3页 / 共5页
第4页 / 共5页
第5页 / 共5页
资料共5页,全文预览结束
c# 串口通讯如何多次重复发送一帧数 据,并且保证发送和回复每一帧数据的 顺序正确 Chouna 发表于 2012-7-31 00:21 1 年前, 3 回/1623 阅, 最后回答: 1 年前 C#串口通讯时,已经实现正确发送数据包,正确得到回复;如何实现若发送失败 最多发送 5 次,并且发送多个数据包时,发送数据和回复数据在界面的显示不串 行;我尝试做过,会出现数据串行,或者一帧数据已成功发送、回复还继续发送 的情况,如图 我的大概思路如下: // 每帧数据发送出去后,等待 500ms 接收返回的数据,若无信息返回,则连续 发送 5 次,5 次都失败则终止操作
view source print? 001 private void SendData(string[] hexString) 002 { 003 004 005 006 007 008 00 9 01 0 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 03 1 for (int i = 0; i < 6; i++) { if (i < 5) { if (!IsReceived) { 16, 0); ); //暂停 500ms WriteTable(hexString[0].Trim(), 2, System.Threading.Thread.Sleep(500 } else { } IsReceived = false; break; } else { } MessageBox.Show("发送错误,无回应数据"); return; } for (int i = 0; i < 6; i++) { if (i < 5) { if (!IsReceived) { WriteTable(hexString[1].Trim(), 18, 0, 1);
03 2 033 034 035 036 037 038 039 040 041 042 043 044 045 ); //暂停 500ms System.Threading.Thread.Sleep(500 } else { } IsReceived = false; break; MessageBox.Show("发送错误,无回应数据"); return; } else { } } 046 } 047 048 049 private void WriteTable(string hexString, int dataLen, int startAddress, int tableType) 050 { 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 byte[] package = new byte[dataLen]; int k = 0; package[0] = 0xAA;//帧头 //帧数据 byte[] bytes = Common.StrToToHexByte(hexString); foreach (byte b in bytes) { } package[k++] = b; //数据包组码 。 。
066 067 068 069 070 071 072 073 074 075 076 。 if (!mycomm.IsOpen) { } MessageBox.Show("串口没有打开,请打开串口!"); return; string data = ByteArrayToHexString(package); textBoxSend.AppendText("发送>>>:" + data + "\n"); mycomm.Write(package, 0, package.Length);//向串口发送一包 的数据 */ 077 } 078 079 private void ReadTable(object sender, SerialDataReceivedEventArgs e) 080 { 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 100 try { string errorInfo = "回复出错"; int n = mycomm.BytesToRead; byte[] buf = new byte[n]; mycomm.Read(buf, 0, n);//读取缓冲数据 //<协议解析> bool data_1_catched = false; //1.缓存数据 buffer.AddRange(buf); //2.完整性判断 while (buffer.Count >= 4) { //2.1 查找帧头 if (buffer[0] == 0xAA) { 。。 。。 。。
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 data_1_catched = true; errorInfo = "帧头错误"; } else { } } if (data_1_catched) { //显示回复的数据 ByteArrayToHexString(binary_data_1) + "\n\n"); this.textBoxSend.AppendText("<<<回复:" + this.textBoxSend.AppendText("\n"); //这个变量表示是否接收到数据,决定是否重复 发送数据,要是改行代码放在该 if 块的第一行,得到的结果不一样,我猜 想是因为显示回复的数据时占用了时间,这个如何设置更合理??? IsReceived = true; } else { errorInfo + "\n\n"); } } catch this.textBoxSend.AppendText("<<<回复:" + { } MessageBox.Show("接受数据时出错"); return; 128 } 标签: C# 我想问同样的问题 共 0个人想要问同样的问题 补充话题说明»
分享到:
收藏