串口通讯模型"/>
C# 带超时处理的串口通讯模型
串口发送与接收数据的模型,带超时功能,示意图如下:
其中,额外等待是可有可无的。
代码如下(已精简,只剩最主要的)。其中串口类的名字是Global.sp
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Diagnostics;namespace Test01
{public partial class FormMain : Form{static System.Timers.Timer timerTOA; //timerTimeOut A 总体观察(暂无数据时)byte[] buff; //临时数组,存放每次的返回结果int delayTime; //允许的超时次数int offset; //当前偏移量int bytesNum; //本次读取到的数量public FormMain(){InitializeComponent();initData();bindEvent();send();}public void initData(){timerTOA = new System.Timers.Timer();timerTOA.Interval = 100; //100ms超时 timerTOA.AutoReset = false;timerTOA.Enabled = false;buff = new byte[1500];offset = 0;bytesNum = 0;delayTime = 0;}public void bindEvent(){timerTOA.Elapsed += new System.Timers.ElapsedEventHandler(end100ms);Global.sp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(spDataReceived);}//串口发送private void send(){byte[] order = "xxxxx";sendOrder(order); //sendOrder不再展开}/// <summary>/// timerTOA的100ms结束时触发的方法/// </summary>private void end100ms(Object sender, EventArgs e){bytesNum = Global.sp.BytesToRead;if (bytesNum == 0 && delayTime <= 10) //再给10次机会{delayTime++;timerTOA.Start();}else{try{if (Global.sp.BytesToRead > 0){Global.sp.Read(buff, 0, Global.sp.BytesToRead);}} catch (Exception ex){//错误处理...}this.BeginInvoke(new EventHandler(analyze));} }/// <summary>/// 串口收到下位机返回的数据时触发的方法/// </summary>public void spDataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e){timerTOA.Stop();timerTOA.Start();}/// <summary>/// 针对本次数据进行分析处理/// </summary>public void analyze(object sender, EventArgs e){//处理数据...//...//处理完毕,开始下一次循环(如果需要的话)reset();//继续...//send()}/// <summary>/// 重置一些内容/// </summary>public void reset(){buff = new byte[1500];offset = 0;bytesNum = 0;delayTime = 0;}}
}
更多推荐
C# 带超时处理的串口通讯模型
发布评论