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

  • 3
  • 0
  • 约1.54万字
  • 约 14页
  • 2023-05-12 发布于上海
  • 举报
K1+478~K1+5888 段左侧片石混凝土挡土墙第 1 部分 PAGE PAGE 10页脚内容 c#上位机串口通信助手源代码实例详 解 一、 功能 软件打开时,自动检测有效 COM 端口 软件打开时,自动复原到上次关闭时的状态 不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位),可按更改后的信息自动将串口重新打开 可统计接收字节和发送字节的个数 接收数据可按 16 进制数据和非 16 进制数据进行整体转换 可将接收到数据进行保存 可设置自动发送,发送时间可进行实时更改 可按字符串、16 进制字节、文件方式进行发送,字符串和16 进制字节可分别进行存储,内容互不干扰 按 16 进制发送时,可自动校验格式,不会输错 可清空发送或接收区域的数据二、 使用工具 Visual Studio2015 三、 程序详解 界面创建 图 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 创建一个方法类 按 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 串口助手 namespace 串口助手sdd { classMethods { //获取有效的COM口publicstaticstring[] ActivePorts() { ArrayList activePorts = newArrayList(); foreach (string pname inSerialPort.GetPortNames()) { activePorts.Add(Convert.ToInt32(pname.Substring(3))); } activePorts.Sort(); string[] mystr = newstring[activePorts.Count]; int i = 0; foreach (int num in activePorts) { mystr[i++] = COM + num.ToString(); } return mystr; } //16进制字符串转换为byte字符数组publicstaticByte[] _16strToHex(string strValues) { string[] hexValuesSplit = strValues.Split( ); Byte[] hexValues = newByte[hexValuesSplit.Length]; Console.WriteLine(hexValuesSplit.Length); for (int i = 0; i hexValuesSplit.Length; i++) { hexValues[i] = Convert.ToByte(hexValuesSplit[i], 16); } return hexValues; } } //byte数组以 //byte数组以16进制形式转字符串publicstaticstring ByteTo16Str(byte[] bytes) { string recData = null;//创建接收数据的字符串 foreach (byte outByte in bytes)//将字节数组以16进制形式遍历到一个字符串内 { recData += outByte.ToString(X2) + ; } return recData; } //16进制字符串

文档评论(0)

1亿VIP精品文档

相关文档