C# 带超时处理的串口通讯模型

编程入门 行业动态 更新时间:2024-10-07 22:18:31

C# 带超时处理的<a href=https://www.elefans.com/category/jswz/34/1769224.html style=串口通讯模型"/>

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# 带超时处理的串口通讯模型

本文发布于:2024-02-14 10:41:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1763211.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:串口   模型   通讯

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!