惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Security Blog
Microsoft Security Blog
S
Secure Thoughts
酷 壳 – CoolShell
酷 壳 – CoolShell
S
SegmentFault 最新的问题
WordPress大学
WordPress大学
Hugging Face - Blog
Hugging Face - Blog
人人都是产品经理
人人都是产品经理
美团技术团队
博客园 - 三生石上(FineUI控件)
Jina AI
Jina AI
V
Visual Studio Blog
腾讯CDC
小众软件
小众软件
有赞技术团队
有赞技术团队
博客园 - 聂微东
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
IT之家
IT之家
C
CERT Recently Published Vulnerability Notes
大猫的无限游戏
大猫的无限游戏
T
Threat Research - Cisco Blogs
SecWiki News
SecWiki News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
宝玉的分享
宝玉的分享
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The Hacker News
The Hacker News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Troy Hunt's Blog
月光博客
月光博客
雷峰网
雷峰网
T
Tor Project blog
I
Intezer
S
Securelist
罗磊的独立博客
The Register - Security
The Register - Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
NISL@THU
NISL@THU
Google Online Security Blog
Google Online Security Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Cisco Talos Blog
Cisco Talos Blog
云风的 BLOG
云风的 BLOG
www.infosecurity-magazine.com
www.infosecurity-magazine.com
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
Lohrmann on Cybersecurity
The Cloudflare Blog
Attack and Defense Labs
Attack and Defense Labs
P
Privacy International News Feed
W
WeLiveSecurity
Forbes - Security
Forbes - Security
量子位
Last Week in AI
Last Week in AI

博客园 - 衡斅

基于.net C# Socket WinForm MQTT 客户端开发 基于.Net C# 通信开发-网络调试助手 基于HBuilderX+UniApp+ColorUi+UniCloud 优宝库 开发实战(一) .net core 跨平台开发 微服务架构 基于Nginx反向代理 服务集群负载均衡 .Net Core 跨平台开发实战-服务器缓存:本地缓存、分布式缓存、自定义缓存 redis 分布式缓存实战-redis 事务 基于.net EF6 MVC5+WEB Api 的Web系统框架总结(4)-Excel文件读、写操作 基于.net EF6 MVC5+WEB Api 的Web系统框架总结(3)-项目依赖注入 基于.net EF6 MVC5+WEB Api 的Web系统框架总结(2)-业务项目搭建 基于.net EF6 MVC5+WEB Api 的Web系统框架总结(1)-Web前端页面 基于html5 plus + Mui 移动App开发(三)-食全库 基于Html5 Plus + Vue + Mui 移动App开发(三)-文件操作(读取、保存、更新数据) 基于Html5 Plus + Vue + Mui 移动App 开发(二) 基于html5 plus + Mui 移动App开发(一) 基于百度地图的产品销售的单位查看功能设计与实现 实全软件产品自动升级管理解决方案 基于服务(Web Service)的文件管理Winform客户端实现(二) 如何通过WPS 2013 API 将Office(Word、Excel和PPT)文件转PDF文件 如何通过SerialPort读取和写入设备COM端口数据
基于.Net C# 通信开发-串口调试助手
衡斅 · 2022-05-03 · via 博客园 - 衡斅

  基于.Net C# 通信开发-串口调试助手

  1、概述

  

  串口调试助手,广泛应用于工控领域的数据监控、数据采集、数据分析等工作,可以帮助串口应用设计、开发、测试人员检查所开发的串口应用软硬件的数据收发状况,提高开发的速度,成为您的串口应用的开发助手。
实全串口调试助手是绿色软件,只有一个执行文件,适用于各版本Windows操作系统,基于C# .Net 4.0 框架开发。可以在一台PC上同时启动多个串口调试助手(使用不同的COM口)。
  典型应用场合:通过串口调试助手与自行开发的串口程序或者串口设备进行通信联调。
  支持多串口,自动监测枚举本地可用串口;自由设置串口号、波特率、校验位、数据位和停止位等(支持自定义非标准波特率);
  支持ASCII/Hex两种模式的数据收发,发送和接收的数据可以UTF-8、16进制和AscII码之间任意转换;
  支持间隔发送,循环发送,批处理发送,输入数据可以从外部文件导入。

  串口调试开发,一般分为读取电脑连接串口信息、选择串口信息进行连接、设置相关发送接收配置、发送命令或消息,接收读取返回结果。

  2、串口开发主要代码

  2.1、读取电脑连接串口信息

  串口调试,首先需要程序读取电脑连接串口信息。

  //读取连接串口
            string[] mPortNames = SerialPort.GetPortNames();
            this.txtPortName.Items.Clear();
            foreach (var item in mPortNames)
            {
                this.txtPortName.Items.Add(item);
            }

            this.txtParity.Items.Clear();
            foreach (string item in Enum.GetNames(typeof(Parity)))
            {
                this.txtParity.Items.Add(item);
            }
            this.txtParity.DropDownStyle = ComboBoxStyle.DropDownList;

            this.txtStopBits.Items.Clear();
            foreach (string item in Enum.GetNames(typeof(StopBits)))
            {
                this.txtStopBits.Items.Add(item);
            }
            this.txtStopBits.DropDownStyle = ComboBoxStyle.DropDownList;

            this.txtHandshake.Items.Clear();
            foreach (string item in Enum.GetNames(typeof(Handshake)))
            {
                this.txtHandshake.Items.Add(item);
            }
            this.txtHandshake.DropDownStyle = ComboBoxStyle.DropDownList;

  2.2、选择串口信息进行连接

/// <summary>
        /// 获取串口信息
        /// </summary>
        /// <param name="setting"></param>
        /// <param name="fail"></param>
        /// <returns></returns>
        public static SerialPort GetSerialPort(SerialPortSet setting, out string fail)
        {
            fail = string.Empty;
            try
            {
                _SerialPort = new SerialPort();
                _SerialPort.PortName = setting.PortName;
                _SerialPort.BaudRate = setting.BaudRate.ToInt32();
                _SerialPort.Parity = (Parity)Enum.Parse(typeof(Parity), setting.Parity, true);
                _SerialPort.DataBits = setting.DataBits.ToInt32();
                _SerialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), setting.StopBits, true);
                _SerialPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), setting.Handshake, true);

                return _SerialPort;
            }
            catch (Exception ex)
            {
                fail = "打开串口 异常:" + ex.Message;
                return null;
            }
        }

  2.3、选择相关发送接收配置

  支持UTF-8、ASCII、GB2312、16进制内容,收、发选择;支持间隔发送,循环发送,批处理发送,输入数据可以从外部文件导入。

  2.4、发送命令或消息

/// <summary>
        /// 发送命令或消息
        /// </summary>
        /// <param name="content"></param>
        private void SendByte(string content)
        {
            try
            {
                if (this.ckbShowSend.Checked)
                    this.AppendText(content);

                byte[] buffer;
                if (this.txtSendEncoding.Text.Length <= 0)
                    buffer = Encoding.Default.GetBytes(this.txtContent.Text);
                else if (this.txtSendEncoding.Text == "16进制")
                    buffer = this.HexToByte(this.txtContent.Text);
                else
                    buffer = Encoding.GetEncoding(this.txtSendEncoding.Text).GetBytes(this.txtContent.Text);
                //向串口发送数据
                this._SerialPort.Write(buffer, 0, buffer.Length);
            }
            catch (Exception ex)
            {
                WinMessageBox.Warning("发送失败:" + ex.Message);
            }
        }

  2.5、接收读取返回结果

/// <summary>
        /// 接收读取返回结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] buffer = new byte[this._SerialPort.ReadBufferSize];
            int count = this._SerialPort.Read(buffer, 0, buffer.Length);
            //string str = Encoding.Default.GetString(readBuffer).TrimEnd('\0');
            if (this.txtEncoding.Text.Length <= 0)
                this.AppendText(System.Text.Encoding.Default.GetString(buffer,0, count));
            else if (this.txtEncoding.Text == "16进制")
                this.AppendText(this.ByteToHex(buffer,0,count));
            else
                this.AppendText(System.Text.Encoding.GetEncoding(this.txtEncoding.Text).GetString(buffer,0,count));
        }

  3、结语

  至此介绍完毕,本项目开源,源码地址:https://gitee.com/ShiQuan25/SerialHelper 

  安装包下载地址:https://gitee.com/ShiQuan25/SerialHelper/attach_files/1048876/download/ShiQuan.SerialHelper.zip

  不当之处,欢迎指正!