private void Form1_Load(object sender, EventArgs e) { FifoClass.InitFifo(); CommPara.ParaRead(); openPort(); if (comm.IsOpen) { comm.DataReceived += comm_DataReceived; } }
public void comm_DataReceived(object sender, SerialDataReceivedEventArgs e) { int i; try { byte[] framebuffer = new byte[128]; byte frametype = 0; int n = CVar.GetComm().BytesToRead;//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致 if (n == 0) { return; } byte[] buf = new byte[n]; //声明一个临时数组存储当前来的串口数据 received_count += n; //增加接收计数 comm.Read(buf, 0, n); //读取缓冲数据 //Add receive data to que for (i = 0; i < n; i++) { FifoClass.EnFifo(buf[i]); } if (GetFrame(ref framebuffer, ref frametype) > 0) { st_CommParaSet commPara = new st_CommParaSet(); commPara = (st_CommParaSet)CommProtocol.BytesToStruct(framebuffer, commPara.GetType()); UploadData.hall_angle = commPara.hall_angle; UploadData.zeroAngle = commPara.hall_zero_angle; UploadData.hall_x = commPara.hall_x; UploadData.hall_y = commPara.hall_y; UploadData.maxDegree = commPara.maxDegree; UploadData.maxCurrent = commPara.maxCurrent; UploadData.Kp = commPara.pid_p; UploadData.Ki = commPara.pid_i; UploadData.Ke1 = commPara.pid_ke1; UploadData.Ke2 = commPara.pid_ke2; UploadData.reversse = commPara.reverse; UploadData.run2zero = commPara.run2zero; UploadData.traceMode = commPara.traceMode; } } finally { } }
public UInt16 GetFrame(ref byte[] buffer, ref byte type) { st_CommParaSet commPara = new st_CommParaSet(); int length = Marshal.SizeOf(commPara); int i; while (true) { if (FifoClass.FifoLen() >= length) { FifoClass.CheckFifo(ref buffer, 4); if (buffer[0] == CommProtocol.CMD_HEAD1 && buffer[1] == CommProtocol.CMD_HEAD2 && buffer[2] == CommProtocol.CMD_HEAD3 && buffer[3] == CommProtocol.CMD_HEAD4) { { for (i = 0; i < (length); i++) { buffer[i] = FifoClass.DeFifo(); } commPara = (st_CommParaSet)CommProtocol.BytesToStruct(buffer, commPara.GetType()); return((UInt16)length); } } else { FifoClass.DeFifo(); } } else { break; } } return(0); }