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;
        }
    }
}

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鹰信息技术服务部

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值