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

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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++] = "COM" + 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);

}

return hexValues;

}

//byte数组以16进制形式转字符串

public static string ByteTo16Str(byte[] bytes)

{

string recData = null;//创建接收数据的字符串

foreach (byte outByte in bytes)//将字节数组以16进制形式遍历到一个字符串内 {

recData += outByte.ToString("X2") + " ";

}

return recData;

}

//16进制字符串转换字符串

public static string _16strToStr(string _16str)

{

string outStr = null;

byte[] streamByte = _16strToHex(_16str);

outStr = Encoding.Default.GetString(streamByte);

return outStr;

}

}

}

2 Form1.cs的代码为:

using System;

using System.Collections.Generic;

using ponentModel;

using System.Data;

using System.Drawing;

using System.IO.Ports;

using System.Linq;

using System.Text;

using System.Text.RegularExpressions;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.IO;

using System.Collections;

namespace串口助手sdd

{

public partial class Form1 : Form

{

//声明变量

SerialPort sp = new SerialPort();

bool isSetProperty = false;//串口属性设置标志位

private enum PortState//声明接口显示状态,枚举型

相关文档
最新文档