问题描述
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.IO.Ports;namespacetiqu{publicpartialclassForm1:Form{privateSerialPortsp;privateCRecvBufrecvBuf;publicForm1(){InitializeComponent();}classCRecvBuf{publicList<byte>li;publicintmaxLength;publicbyte[]getAllData(){byte[]x=newbyte[li.Count];for(inti=0;i<li.Count;i++){x[i]=li[i];}returnx;}publicCRecvBuf(intmaxLength){li=newList<byte>();this.maxLength=maxLength;}publicvoidAdd(byte[]b){if(b.Length>maxLength)thrownewException("接收到的数据量超出缓冲区的长度");li.AddRange(b);if(li.Count>maxLength)li.RemoveRange(0,li.Count-maxLength);}}publicclassCCheck{publicstaticstringBinaryToHexString(byte[]buff){StringBuildertmp=newStringBuilder();for(inti=0;i<buff.Length;i++)tmp.Append(buff[i].ToString("X2")+"");returntmp.ToString().Trim();}}privatevoidbutton1_Click(objectsender,EventArgse){bytefirstByte;byte[]tmp;sp.ReadTimeout=10000;try{firstByte=(byte)sp.ReadByte();tmp=newbyte[sp.BytesToRead+1];tmp[0]=firstByte;sp.Read(tmp,1,tmp.Length-1);textBox1.Text=CCheck.BinaryToHexString(tmp);recvBuf.Add(tmp);textBox2.Text=CCheck.BinaryToHexString(recvBuf.getAllData());tmp=getBlock(recvBuf.li);if(tmp!=null)textBox3.Text=CCheck.BinaryToHexString(tmp);elsetextBox3.Text="";}catch(TimeoutExceptionex){textBox1.Text=ex.Message;}}privatevoidtextBox3_TextChanged(objectsender,EventArgse){}privatevoidForm1_Load(objectsender,EventArgse){recvBuf=newCRecvBuf(60);sp=newSerialPort("COM1",9600,Parity.None,8,StopBits.One);sp.Open();}privatevoidForm1_FormClosing(objectsender,FormClosingEventArgse){if(sp!=null&&sp.IsOpen)sp.Close();}privatebyte[]getBlock(List<byte>li){byte[]b=null;if(li.Count<30)returnb;intp=li.Count;while((p=li.LastIndexOf(0x12,p-1))!=-1)if(li.Count>=p+30)if(li[p+1]==0x34&&li[p+2]==0x56)break;if(p!=-1){b=newbyte[30];li.CopyTo(p,b,0,30);}returnb;}}}以上为接受一个完整数据帧,怎样才能对数据帧解码?请各位高手说说啊。先谢谢了。
解决方案
解决方案二:
你得知道通信协议才能解码,不然你只能显示每个字节的值,至于哪几个字节组合成一个数字你是不知道的
解决方案三:
比如收到6个字节数据,协议如下:0XAA(报文头)+电流低字节+电流高字节+电压低字节+电压高字节+CRC这样你知道:第一个字节0XAA是报文头,第二个和第三个组合成电流值:电流=receBuff[2]<<256+receBuff[1];电压=receBuff[4]<<256+receBuff[3];,最后一个是CRC,是用来判断接收数据是否正确