c#上位机串口通信助手源代码详解 下载本文

内容发布更新时间 : 2024/5/20 3:53:55星期一 下面是文章的全部内容请认真阅读。

c#上位机串口通信助手源代码实例详解

一、 功能

1软件打开时,自动检测有效COM端口 2 软件打开时,自动复原到上次关闭时的状态

3 不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位),可按更改后的信息自动将串口重新打开 4 可统计接收字节和发送字节的个数

5 接收数据可按16进制数据和非16进制数据进行整体转换 6 可将接收到数据进行保存

7 可设置自动发送,发送时间可进行实时更改

8可按字符串、16进制字节、文件方式进行发送,字符串和16进制字节可分别进行存储,内容互不干扰

9 按16进制发送时,可自动校验格式,不会输错 10 可清空发送或接收区域的数据

二、 使用工具

Visual Studio2015

三、 程序详解

1 界面创建

图1

用winform创建如图1所示界面,控件名字分别为: 端口号:cbxCOMPort 波特率:cbxBaudRate 数据位:cbxDataBits 停止位:cbxStopBits 校验位:label5

打开串口按钮:btnOpenCom 发送(byte):tbSendCount 接收(byte):tbReceivedCount 清空计数按钮:btnClearCount 按16进制显示:cb16Display

接收区清空内容按钮:btnClearReceived 保存数据按钮:btnSaveFile 接收数据框:tbReceivedData

发送数据框:tbSendData 自动发送:cbAutomaticSend 间隔时间:tbSpaceTime 按16进制发送:cb16Send

发送区清空内容按钮:btnClearSend 读入文件按钮:btnReadFile 发送按钮:btnSend 2 创建一个方法类

按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:

using System;

using System.Collections;

using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text;

using System.Threading.Tasks;

namespace 串口助手sdd {

class Methods {

//获取有效的COM口

public static string[] ActivePorts() {

ArrayList activePorts = new ArrayList();

foreach (string pname in SerialPort.GetPortNames()) {

activePorts.Add(Convert.ToInt32(pname.Substring(3))); }

activePorts.Sort();

string[] mystr = new string[activePorts.Count]; int i = 0;

foreach (int num in activePorts) {

mystr[i++] = \ + num.ToString(); }

return mystr; }

//16进制字符串转换为byte字符数组

public static Byte[] _16strToHex(string strValues) {

string[] hexValuesSplit = strValues.Split(' ');

Byte[] hexValues = new Byte[hexValuesSplit.Length]; Console.WriteLine(hexValuesSplit.Length); for (int i = 0; i < hexValuesSplit.Length; i++) {

hexValues[i] = Convert.ToByte(hexValuesSplit[i], 16);