版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、c# 上位机串口通信助手源代码实例详解功能软件打开时,自动检测有效 COM 端口软件打开时,自动复原到上次关闭时的状态不必关闭串口,即可直接进行更改初始化设置内容串口号、波特率、数据位、停止位、校验位,可按更改后的信息自动将串口重新打开可统计接收字节和发送字节的个数接收数据可按 16 进制数据和非 16 进制数据进行整体转换可将接收到数据进行保存可设置自动发送,发送时间可进行实时更改可按字符串、 16 进制字节、文件方式进行发送,字符串和 16 进制字节可分别进 行存储,内容互不干扰按 16进制发送时,可自动校验格式,不会输错可清空发送或接收区域的数据使用工具Visual Studio2015
2、程序详解1 界面创建图1用winform创建如图1所示界面,控件名字分别为:端口号:cbxCOMPort数据位:cbxDataBits校验位:Iabel5发送byte: tbSendCount清空计数按钮:bt nClearCou nt接收区清空内容按钮:bt nClearReceived接收数据框:tbReceivedData自动发送:cbAutomaticSe nd按16进制发送:cb16Send读入文件按钮:btn ReadFile波特率:cbxBaudRate停止位:cbxStopBits打开串口按钮:bt nOpe nCom 接收byte: tbReceivedCount 按16进制
3、显示:cb16Display 保存数据按钮:bt nSaveFile发送数据框:tbSe ndData间隔时间:tbSpaceTime发送区清空内容按钮:bt nClearSe nd发送按钮:btnSend2创建一个方法类按Ctrl+shift+A 快捷键创建一个类,名字叫 Methods,代码为: using System;using System.Collections;using System.Collections.Generic;using System.10.Ports;using System.Linq;using System.Text;using System.Threadi
4、ng.Tasks;namespace 串 口助手 sddclass Methods/获取有效的COI口public staticstring ActivePorts()ArrayList activePorts = new ArrayList (); foreach ( string pname in SerialPort .GetPortNames()activePorts.Add(Con vert .ToI nt32(p name.Substri ng(3);activePorts.Sort();string mystr = new string activePorts.Count; in
5、t i = 0;foreach ( int num in activePorts)mystri+ =COM+ num.ToStri ng();return mystr;16进制字符串转换为byte字符数组public static Byte _16strToHex(stri ng strValues) _string hexValuesSplit = strValues.Split();Byte hexValues = new Byte hexValuesSplit.Length;Co nsole.WriteLi ne(hexValuesSplit.Le ngth);for (int i =
6、0; i hexValuesSplit.Length; i+)hexValuesi =Convert .ToByte(hexValuesSpliti, 16);retur n hexValues;/byte数组以16进制形式转字符串public staticstring ByteTo16Str( byte bytes)string recData = null ; /创建接收数据的字符串foreach ( byte outByte in bytes) /将字节数组以16进制形式遍历到一个字符串内recData += outByte.ToString(X2) + ;return recData;
7、16进制字符串转换字符串public staticstr ing _16strToStr( stri ng _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 System.ComponentModel;using System.Data;using S
8、ystem.Drawing;using System.10.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 串 口助手 sddpublic partial class Form1 : Form/声明变量SerialPort sp = new SerialPort ();boo
9、l isSetProperty = false ;/ 串口属性设置标志位private enumPortState /声明接口显示状态,枚举型打开,关闭stri ng path = AppDoma in Curre ntDoma in .BaseDirectory +confin g.i ni; / 声明配置文件路径string tbSendDataStr = ; / 发送窗口字符串存储string tbSendData16 = ; / 发送窗口 16进制存储List receivedDatas = new List (); / 接收数据泛型数组/接收串口数据private void sp_D
10、ataReceived( object sender, SerialDataReceivedEventArgs e) byte ReceivedData = new byte sp.BytesToRead; / 创建接收字节数组 sp.Read(ReceivedData, 0, ReceivedData.Length);/ 读取所接收到的数据receivedDatas.AddRa nge(ReceivedData);tbReceivedCount.Text = (Convert .ToInt32(tbReceivedCount.Text) +ReceivedData.Le ngth).ToSt
11、ri ng();if (cb16Display.Checked) _|tbReceivedData.Text =Methods.ByteTo16Str(receivedDatas.ToArray();elsetbReceivedData.Text =Encoding .Default.GetString(receivedDatas.ToArray();sp.DiscardInBuffer();/丢弃接收缓冲区数据/发送串口数据private void DataSend()tryif (cb16Send.Checked)byte hexBytes =Methods._16strToHex(tbS
12、endData16);sp.Write(hexBytes, 0, hexBytes.Le ngth);tbSendCount.Text = (Convert .ToInt32(tbSendCount.Text) +hexBytes.Le ngth).ToStri ng();elsesp.WriteLi ne(tbSe ndDataStr);tbSendCount.Text = (Convert .ToInt32(tbSendCount.Text) +tbSe ndDataStr.Le ngth).ToStri ng(); catch ( Exception ex)MessageBoxShow(
13、ex.Message.ToStri ng(); return ;/设置串口属性private void SetPortProperty() sp.PortName = cbxCOMPort.Text.Trim();/ 设置串口名sp.BaudRate =Con vert .ToI nt32(cbxBaudRate.Text.Trim(); / 设置波特率switch (cbxStopBits.Text.Trim() / 设置停止位case 1 : sp.StopBits = StopBits .One; break;case 1.5 : sp.StopBits = StopBits .OneP
14、ointFive;break ;case 2 : sp.StopBits = StopBits .Two; break; default : sp.StopBits = StopBits .None; break;sp.DataBits =Con vert .ToI nt32(cbxDataBits.Text.Trim();/ 设置数据位switch (cbxParity.Text.Trim() / 设置奇偶校验位case 无:sp.Parity = Parity .None; break ;case 奇校验:sp.Parity =Parity .Odd; break;case 偶校验:sp.
15、Parity =Parity .Even; break;default : sp.Parity = Parity .None; break ;sp.ReadTimeout = 5000;/ 设置超时时间为 5sControl .CheckForlllegalCrossThreadCalls = false ;/ 这个类中我们不检查跨线程 的调用是否合法(因为.net 2.0以后加强了安全机制,不允许在winform中直接跨线程访问控件的属 性)/定义DataReceived事件的委托,当串口收到数据后岀发事件sp.DataReceived +=new SerialDataReceivedEve
16、ntHandler(sp_DataReceived);/设置端口显示状态private void DisplayPortState( PortState portState)toolStripStatusLabel1.Text = cbxCOMPort.Text +端口 处于+ portState +状态+ cbxBaudRate.Text + + cbxDataBits.Text + + cbxStopBits.Text + +cbxParity.Text;/重新打开串口private void AgainOpenPort()if (sp.IsOpen)trytrue ;sp.Close()
17、; SetPortProperty(); isSetProperty =btnOpenCom.Text =打开串口 ”;DisplayPortState(PortState .关闭);MessageBoxShow(”串口无效或已被占用!,错误提示); return ;DisplayPortState(PortState .打开);public Form1()In itializeComp onen t();/软件启动时加载事件private void Form1_Load( object sender,EventArgs e)#region加载配置文件Hashtable ht = new Ha
18、shtable ();if ( File .Exists(path)trystring myline =;string str = new string 2;using ( StreamReader sr = new StreamReader(path) myli ne = sr.ReadL in e();while (myline !=null )str = myline.Split(=);ht.Add(strO, str1);myli ne = sr.ReadL in e();catch ( Exception ex)MessageBoxShow(ex.Message.ToStri ng(
19、);#en dregi on#region设置窗口为固定大小且不可最大化this .MaximumSize = this .Size;this .MinimumSize = this .Size;this .MaximizeBox = false ;#en dregi on#region列岀常用的波特率cbxBaudRate.ltems.Add(1200);cbxBaudRate.Items.Add(2400);cbxBaudRate.Items.Add(4800);cbxBaudRate.Items.Add(9600);cbxBaudRate.Items.Add(19200);cbxBaud
20、Rate.Items.Add(38400)cbxBaudRate.Items.Add(43000);cbxBaudRate.Items.Add(56000);cbxBaudRate.Items.Add(57600);cbxBaudRate.Items.Add(115200);if (ht.ContainsKey(cbxBaudRate)cbxBaudRate.Selectedl ndex =cbxBaudRate.Items.IndexOf(ht cbxBaudRate .ToString();elsecbxBaudRate.SelectedI ndex = 3;cbxBaudRate.Dro
21、pDow nStyle =ComboBoxStyle. DropDow nList;#en dregi on#regio n列岀停止位cbxStopBits.ltems.Add( cbxStopBits.ltems.Add( cbxStopBits.ltems.Add(if (ht.ContainsKey(1);1.52););cbxStopBits)ComboBoxStyle. DropDow nList;8);7);6);5);cbxDataBits)ComboBoxStyle. DropDow nList;#regi on列岀奇偶校验位cbxStopBits.SelectedI ndex
22、 =cbxStopBits.Items.I ndexOf(htcbxStopBits .ToStrin g();elsecbxStopBits.SelectedI ndex = 0; cbxStopBits.DropDow nStyle = #en dregi on#region列岀数据位cbxDataBits.Items.Add(cbxDataBits.Items.Add(cbxDataBits.Items.Add(cbxDataBits.Items.Add(if (ht.ContainsKey(cbxDataBits.Selectedl ndex =cbxDataBits.Items.I
23、ndexOf(htcbxDataBits .ToStr in g();elsecbxDataBits.Selectedl ndex = 0; cbxDataBits.DropDow nStyle = #en dregi on无);奇校验);偶校验);cbxParity)cbxParity.ltems.Add(cbxParity.ltems.Add(cbxParity.Items.Add(if (ht.ContainsKey(cbxParity.Selectedl ndex =cbxParity.Items. In dexOf(htcbxParity .ToStri ng();elsecbxPa
24、rity.Selectedl ndex = 0;ComboBoxStyle.DropDow nList;cbxParity.DropDow nStyle =#en dregi on#regio nCOM口重新加载cbxCOMPort.ltems.Clear();/清除当前串口号中的所有串口名称cbxCOMPort.ltems.AddRa nge(Methods.ActivePorts();if (ht.ContainsKey(cbxCOMPort) &cbxCOMPort.ltems.Co ntai ns(ht cbxCOMPort .ToStri ng() cbxCOMPort.Select
25、edl ndex =cbxCOMPort.ltems.l ndexOf(htcbxCOMPort.ToStri ng();elsecbxCOMPort.Selected In dex = 0;cbxCOMPort.DropDow nStyle =ComboBoxStyleDropDow nList;#en dregi on#region初始化计数器tbSendCount.Text =0;tbSendCount.ReadOnly =true ;tbReceivedCount.Text =0;tbReceivedCount.ReadOnly =true ;#en dregi on#region初始
26、化当前时间toolStripStatusLabel3.Text =DateTime.Now.ToStri ng();#en dregi on#regio n初始化串口状态toolStripStatusLabel1.ForeColor =Color .Blue;if (!isSetProperty) /串口未设置则设置串口属性catch ( Exception )/串口打开失败后,串口属性设置标志位设为falseisSetProperty =false ;MessageBoxShow(”串口无效或已被占用!,错误提示);#en dregi on#regio n初始化间隔时间if (ht.Cont
27、ainsKey(tbSpaceTime)tbSpaceTime.Text = httbSpaceTime .ToString();elsetbSpaceTime.Text =1000;#en dregi on#regi on初始化按16进制显示状态if (ht.ContainsKey(cb16Display ) & ht cb16Display .ToString() =True)cb16Display.Checked =true ;else |cb16Display.Checked =false ;#en dregi on#region初始化按16进制发送状态|if (ht.Contains
28、Key(cb16Send) & ht cb16Send.ToString() = True)cb16Send.Checked =true ;elsecb16Send.Checked =false ;#en dregi on#region初始化发送区文本if (ht.ContainsKey( tbSendData16 ) & ht.ContainsKey(tbSendDataStr) tbSendData16 = httbSendData16 .ToString();tbSendDataStr = httbSendDataStr .ToString();if (cb16Send.Checked)
29、tbSendData.Text = httbSendData16 .ToString();elsetbSendData.Text = httbSendDataStr .ToString();#en dregi ontbSe ndData.Focus();/显示当前时间private void timer1_Tick( object sender, EventArgs e) ItoolStripStatusLabel3.Text =DateTime.Now.ToStri ng();/点击打开串口按钮private void btnOpenCom_Click( object sender,Even
30、tArgs e) -if (!sp.lsOpen)/串口没有打开时if (!isSetProperty) /串口未设置则设置串口属性SetPortProperty();true ;sp.Ope n();btnOpenCom.Text =关闭串口 “isSetProperty =DisplayPortState(PortState .打开); | : catch ( Exception )/串口打开失败后,串口属性设置标志位设为falseisSetProperty =false ;MessageBoxShow(”串口无效或已被占用!,错误提示);else /串口已经打开trysp.Close()
31、;isSetProperty =false ;btnOpenCom.Text =打开串口 ”;DisplayPortState(PortState .关闭);catch ( Exception )MessageBoxShow(“关闭串口时发生错误,“错误提示);/发送串口数据private void btnSend_Click( object sender,EventArgs e)if (tbSendData.Text.Trim()=)/检测发送数据是否为空MessageBoxShow(“请输入要发送的数据!,“错误提示); return ;/点击端口号选择下拉框按钮private void
32、cbxCOMPort_SelectedIndexChanged( object sender.EventArgs e)Agai nO pe nPort();/点击波特率选择下拉框按钮private void cbxBaudRate_SelectedIndexChanged( object sender,EventArgs e) 一Agai nO pe nPort();点击数据位选择下拉框按钮private void cbxDataBits_Se ectedIndexChanged(object sender,EventArgs e)Agai nO pe nPort();点击停止位选择下拉框按钮
33、private void cbxStopBits_SelectedIndexChanged(object sender,EventArgs e)Agai nO pe nPort();/点击校验位选择下拉框按钮private void cbxParity_SelectedIndexChanged(object sender, EventArgs e)Agai nO pe nPort();点击数据接收区清空按钮private void btnClearReceived_Click( object sender,EventArgs e) _receivedDatas.Clear();tbReceiv
34、edData.Text =;/点击是否按16进制显示接收数据private void cb16Display_CheckedChanged( object sender, EventArgs e)if (cb16Display.Checked) |tbReceivedData.Text =Methods.ByteTo16Str(receivedDatas.ToArray();elsetbReceivedData.Text =Encoding .Default.GetString(receivedDatas.ToArray();点击是否按16进制发送数据private void cb16Send
35、_CheckedChanged(object sender. EventArgs e) _if (cb16Send.Checked)tbSe ndData.Text = tbSe ndData16;elsetbSe ndData.Text = tbSe ndDataStr;/发送文本框键盘按键检测private void tbSe ndData_KeyPress(object sen der, KeyPressEve ntArgs e)if (cb16Se nd.Checked)/正则匹配stri ng pattern = 0-9a-fA-F|b;/b:退格键Match m = Regex.M
36、atch(e.KeyChar.ToStri ng(), pattern);if (m.Success)if(e.KeyChar != b)if (tbSendData.Text.Length % 3 = 2)tbSe ndData.Text +=;tbSe ndData.Selecti on Start = tbSe ndData.Text Le ngth;e.KeyChar = Co nvert.ToChar(e.KeyChar.ToStri ng().ToUpper();e.Ha ndled = false;elsee.Ha ndled = true;elsee.Ha ndled = fa
37、lse;点击清空发送内容private void btnClearSend_Click(object sender, EventArgs e)tbSendData.Text =;if (cb16Send.Checked)tbSe ndData16 =JelsetbSe ndDataStr =III!.J点击清空计数器数据private void btnClearCount_Click( object sender. EventArgs e) _tbReceivedCount.Text =0;tbSendCount.Text =0;/点击是否设置自动发送private void cbAutoma
38、ticSend_CheckedChanged( object sender, EventArgs e) 一if (cbAutomaticSend.Checked) timer2.Enabled =true ;timer2.Interval =Convert .ToInt32(tbSpaceTime.Text);elsetimer2.Enabled =false ;/自动发送时间文本框键盘按键检测private void tbSpaceTime_KeyPress( object sender,KeyPressEventArgs e) _/正则匹配stri ng pattern =0-9|b;Ma
39、tch m = RegexMatch(e.KeyChar.ToStri ng(),pattern);if (m.Success)timer2.Interval =Convert .ToInt32(tbSpaceTime.Text);e.Handled =false ;elsee.Handled =true ;/串口显示状态cbAutomaticSend.Checked =false ;MessageBoxShow(“串口未打开!,错误提示);returnif (tbSendData.Text.Trim() =)/ 检测发送数据是否为空timer2.Enabled =false ;cbAutom
40、aticSend.Checked =false ;MessageBoxShow(“请输入要发送的数据!,“错误提示); return ;/关闭窗口时出发的事件private void Form1_FormClosed(object sen der, FormClosedEve ntArgs e) _tryusing (StreamWriter sw = new StreamWriter(path, false)sw.WriteLi ne(cbxCOMPort= + cbxCOMPort.Text);sw.WriteLi ne(cbxBaudRate= + cbxBaudRate.Text);sw.WriteLi ne(cbxDataBits= + cbxDataBits.Text);sw.WriteLi ne(cbxStopBits= + cbxStopBits.Text);sw.WriteLi ne(cbxParity= + cbxParity.Text);sw.WriteLi ne(cb16Display=+ cb16Display.Checked.ToStri ng();sw.WriteL in e(tbSpaceTime= + tbSpaceTime.Text);sw.
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 吉林师范大学《团体心理咨询》2021-2022学年第一学期期末试卷
- 吉林师范大学《色彩人体技法解析》2021-2022学年第一学期期末试卷
- 吉林师范大学《教育科学研究方法》2021-2022学年第一学期期末试卷
- 吉林师范大学《高频电子线路》2021-2022学年期末试卷
- 一年级语文下册教学资源整合总结
- 吉林师范大学《多声部听觉训练与写作表演》2021-2022学年第一学期期末试卷
- 吉林大学《装备与制造系统》2021-2022学年第一学期期末试卷
- 2024常用的租赁合同范本
- 汽车产业供应链物流信息化方案
- 建筑工程环境保护施工方案
- 六年级道德与法治期末测试卷加答案(易错题)
- 三位数除以两位数300题-整除-有标准答案
- 办公室装修工程施工方案讲义
- 医院护理人文关怀实践规范专家共识
- 中国农业银行贷后管理办法
- MOOC 陶瓷装饰·彩绘-无锡工艺职业技术学院 中国大学慕课答案
- 小学科学苏教版四年级上册全册教案(2023秋新课标版)
- 信访纠纷化解预案
- 硅晶圆缺陷的化学性质与影响
- 《布的基本知识》课件
- (高清版)TDT 1031.6-2011 土地复垦方案编制规程 第6部分:建设项目
评论
0/150
提交评论