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

上传人:PIYPING 文档编号:11092032 上传时间:2021-06-29 格式:DOCX 页数:15 大小:232.53KB
返回 下载 相关 举报
c#上位机串口通信助手源代码详解.docx_第1页
第1页 / 共15页
c#上位机串口通信助手源代码详解.docx_第2页
第2页 / 共15页
c#上位机串口通信助手源代码详解.docx_第3页
第3页 / 共15页
c#上位机串口通信助手源代码详解.docx_第4页
第4页 / 共15页
c#上位机串口通信助手源代码详解.docx_第5页
第5页 / 共15页
点击查看更多>>
资源描述

《c#上位机串口通信助手源代码详解.docx》由会员分享,可在线阅读,更多相关《c#上位机串口通信助手源代码详解.docx(15页珍藏版)》请在三一文库上搜索。

1、实用标准文案c#上位机串口通信助手源代码实例详解一、功能1软件打开时,自动检测有效COM端口2软件打开时,自动复原到上次关闭时的状态3不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位),可按更改后的信息自动将串口重新打开4可统计接收字节和发送字节的个数5接收数据可按16进制数据和非16进制数据进行整体转换6可将接收到数据进行保存7可设置自动发送,发送时间可进行实时更改8可按字符串、16进制字节、文件方式进行发送,字符串和16进制字节可分别进行存储,内容互不干扰9按16进制发送时,可自动校验格式,不会输错10可清空发送或接收区域的数据二、使用工具VisualS

2、tudio2015三、程序详解1界面创建精彩文档实用标准文案图1用winform创建如图1所示界面,控件名字分别为:端口号:cbxCOMPort波特率:cbxBaudRate数据位:cbxDataBits停止位:cbxStopBits校验位:label5打开串口按钮:btnOpenCom发送(byte):tbSendCount接收(byte):tbReceivedCount清空计数按钮:btnClearCount按16进制显示:cb16Display接收区清空内容按钮:btnClearReceived保存数据按钮:btnSaveFile接收数据框:tbReceivedData发送数据框:tbS

3、endData自动发送:cbAutomaticSend间隔时间:tbSpaceTime按16进制发送:cb16Send发送区清空内容按钮:btnClearSend读入文件按钮:btnReadFile发送按钮:btnSend2创建一个方法类按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.IO.Ports;usingSystem.Linq;usingSystem.Text;usingSystem.Threading

4、.Tasks;namespace串口助手sddclassMethods/获取有效的COM口publicstaticstringActivePorts()ArrayListactivePorts=newArrayList();foreach(stringpnameinSerialPort.GetPortNames()activePorts.Add(Convert.ToInt32(pname.Substring(3);activePorts.Sort();stringmystr=newstringactivePorts.Count;精彩文档实用标准文案inti=0;foreach(intnumin

5、activePorts)mystri+=COM+num.ToString();returnmystr;/16进制字符串转换为byte字符数组publicstaticByte_16strToHex(stringstrValues)stringhexValuesSplit=strValues.Split();BytehexValues=newBytehexValuesSplit.Length;Console.WriteLine(hexValuesSplit.Length);for(inti=0;ihexValuesSplit.Length;i+)hexValuesi=Convert.ToByte(

6、hexValuesSpliti,16);returnhexValues;/byte数组以16进制形式转字符串publicstaticstringByteTo16Str(bytebytes)stringrecData=null;/创建接收数据的字符串foreach(byteoutByteinbytes)/将字节数组以16进制形式遍历到一个字符串内recData+=outByte.ToString(X2)+;returnrecData;/16进制字符串转换字符串publicstaticstring_16strToStr(string_16str)stringoutStr=null;bytestre

7、amByte=_16strToHex(_16str);outStr=Encoding.Default.GetString(streamByte);returnoutStr;2Form1.cs的代码为:usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;精彩文档实用标准文案usingSystem.Drawing;usingSystem.IO.Ports;usingSystem.Linq;usingSystem.Text;usingSystem.Text.RegularExp

8、ressions;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;usingSystem.IO;usingSystem.Collections;namespace串口助手sddpublicpartialclassForm1:Form/声明变量SerialPortsp=newSerialPort();boolisSetProperty=false;/串口属性设置标志位privateenumPortState/声明接口显示状态,枚举型打开,关闭stringpath=AppDomain.CurrentDomain.BaseDirectory

9、+confing.ini;/声明配置文件路径stringtbSendDataStr=;/发送窗口字符串存储stringtbSendData16=;/发送窗口16进制存储ListreceivedDatas=newList();/接收数据泛型数组/接收串口数据privatevoidsp_DataReceived(objectsender,SerialDataReceivedEventArgse)byteReceivedData=newbytesp.BytesToRead;/创建接收字节数组sp.Read(ReceivedData,0,ReceivedData.Length);/读取所接收到的数据r

10、eceivedDatas.AddRange(ReceivedData);tbReceivedCount.Text=(Convert.ToInt32(tbReceivedCount.Text)+ReceivedData.Length).ToString();if(cb16Display.Checked)tbReceivedData.Text=Methods.ByteTo16Str(receivedDatas.ToArray();elsetbReceivedData.Text=Encoding.Default.GetString(receivedDatas.ToArray();sp.Discard

11、InBuffer();/丢弃接收缓冲区数据/发送串口数据privatevoidDataSend()tryif(cb16Send.Checked)bytehexBytes=Methods._16strToHex(tbSendData16);sp.Write(hexBytes,0,hexBytes.Length);tbSendCount.Text=(Convert.ToInt32(tbSendCount.Text)+hexBytes.Length).ToString();精彩文档实用标准文案elsesp.WriteLine(tbSendDataStr);tbSendCount.Text=(Conv

12、ert.ToInt32(tbSendCount.Text)+tbSendDataStr.Length).ToString();catch(Exceptionex)MessageBox.Show(ex.Message.ToString();return;/设置串口属性privatevoidSetPortProperty()sp.PortName=cbxCOMPort.Text.Trim();/设置串口名sp.BaudRate=Convert.ToInt32(cbxBaudRate.Text.Trim();/设置波特率switch(cbxStopBits.Text.Trim()/设置停止位case

13、1:sp.StopBits=StopBits.One;break;case1.5:sp.StopBits=StopBits.OnePointFive;break;case2:sp.StopBits=StopBits.Two;break;default:sp.StopBits=StopBits.None;break;sp.DataBits=Convert.ToInt32(cbxDataBits.Text.Trim();/设置数据位switch(cbxParity.Text.Trim()/设置奇偶校验位case无:sp.Parity=Parity.None;break;case奇校验:sp.Par

14、ity=Parity.Odd;break;case偶校验:sp.Parity=Parity.Even;break;default:sp.Parity=Parity.None;break;sp.ReadTimeout=5000;/设置超时时间为5sControl.CheckForIllegalCrossThreadCalls=false;/这个类中我们不检查跨线程的调用是否合法(因为.net2.0以后加强了安全机制,,不允许在winform中直接跨线程访问控件的属性)/定义DataReceived事件的委托,当串口收到数据后出发事件sp.DataReceived+=newSerialDataRe

15、ceivedEventHandler(sp_DataReceived);/设置端口显示状态privatevoidDisplayPortState(PortStateportState)toolStripStatusLabel1.Text=cbxCOMPort.Text+端口处于+portState+状态+cbxBaudRate.Text+cbxDataBits.Text+cbxStopBits.Text+cbxParity.Text;/重新打开串口privatevoidAgainOpenPort()if(sp.IsOpen)精彩文档实用标准文案trysp.Close();SetPortProp

16、erty();isSetProperty=true;sp.Open();catch(Exception)isSetProperty=false;btnOpenCom.Text=打开串口;DisplayPortState(PortState.关闭);MessageBox.Show(串口无效或已被占用!,错误提示);return;DisplayPortState(PortState.打开);elseDisplayPortState(PortState.关闭);publicForm1()InitializeComponent();/软件启动时加载事件privatevoidForm1_Load(obj

17、ectsender,EventArgse)#region加载配置文件Hashtableht=newHashtable();if(File.Exists(path)trystringmyline=;stringstr=newstring2;using(StreamReadersr=newStreamReader(path)myline=sr.ReadLine();while(myline!=null)str=myline.Split(=);ht.Add(str0,str1);myline=sr.ReadLine();精彩文档实用标准文案catch(Exceptionex)MessageBox.S

18、how(ex.Message.ToString();#endregion#region设置窗口为固定大小且不可最大化this.MaximumSize=this.Size;this.MinimumSize=this.Size;this.MaximizeBox=false;#endregion#region列出常用的波特率cbxBaudRate.Items.Add(1200);cbxBaudRate.Items.Add(2400);cbxBaudRate.Items.Add(4800);cbxBaudRate.Items.Add(9600);cbxBaudRate.Items.Add(19200)

19、;cbxBaudRate.Items.Add(38400);cbxBaudRate.Items.Add(43000);cbxBaudRate.Items.Add(56000);cbxBaudRate.Items.Add(57600);cbxBaudRate.Items.Add(115200);if(ht.ContainsKey(cbxBaudRate)cbxBaudRate.SelectedIndex=cbxBaudRate.Items.IndexOf(htcbxBaudRate.ToString();elsecbxBaudRate.SelectedIndex=3;cbxBaudRate.Dr

20、opDownStyle=ComboBoxStyle.DropDownList;#endregion#region列出停止位cbxStopBits.Items.Add(1);cbxStopBits.Items.Add(1.5);cbxStopBits.Items.Add(2);if(ht.ContainsKey(cbxStopBits)cbxStopBits.SelectedIndex=cbxStopBits.Items.IndexOf(htcbxStopBits.ToString();elsecbxStopBits.SelectedIndex=0;cbxStopBits.DropDownSty

21、le=ComboBoxStyle.DropDownList;#endregion#region列出数据位cbxDataBits.Items.Add(8);cbxDataBits.Items.Add(7);cbxDataBits.Items.Add(6);cbxDataBits.Items.Add(5);if(ht.ContainsKey(cbxDataBits)cbxDataBits.SelectedIndex=cbxDataBits.Items.IndexOf(htcbxDataBits.ToString();else精彩文档实用标准文案cbxDataBits.SelectedIndex=0

22、;cbxDataBits.DropDownStyle=ComboBoxStyle.DropDownList;#endregion#region列出奇偶校验位cbxParity.Items.Add(无);cbxParity.Items.Add(奇校验);cbxParity.Items.Add(偶校验);if(ht.ContainsKey(cbxParity)cbxParity.SelectedIndex=cbxParity.Items.IndexOf(htcbxParity.ToString();elsecbxParity.SelectedIndex=0;cbxParity.DropDownSt

23、yle=ComboBoxStyle.DropDownList;#endregion#regionCOM口重新加载cbxCOMPort.Items.Clear();/清除当前串口号中的所有串口名称cbxCOMPort.Items.AddRange(Methods.ActivePorts();if(ht.ContainsKey(cbxCOMPort)&cbxCOMPort.Items.Contains(htcbxCOMPort.ToString()cbxCOMPort.SelectedIndex=cbxCOMPort.Items.IndexOf(htcbxCOMPort.ToString();el

24、secbxCOMPort.SelectedIndex=0;cbxCOMPort.DropDownStyle=ComboBoxStyle.DropDownList;#endregion#region初始化计数器tbSendCount.Text=0;tbSendCount.ReadOnly=true;tbReceivedCount.Text=0;tbReceivedCount.ReadOnly=true;#endregion#region初始化当前时间toolStripStatusLabel3.Text=DateTime.Now.ToString();#endregion#region初始化串口状

25、态toolStripStatusLabel1.ForeColor=Color.Blue;if(!isSetProperty)/串口未设置则设置串口属性SetPortProperty();isSetProperty=true;trysp.Open();btnOpenCom.Text=关闭串口;DisplayPortState(PortState.打开);catch(Exception)/串口打开失败后,串口属性设置标志位设为falseisSetProperty=false;精彩文档实用标准文案MessageBox.Show(串口无效或已被占用!,错误提示);#endregion#region初始

26、化间隔时间if(ht.ContainsKey(tbSpaceTime)tbSpaceTime.Text=httbSpaceTime.ToString();elsetbSpaceTime.Text=1000;#endregion#region初始化按16进制显示状态if(ht.ContainsKey(cb16Display)&htcb16Display.ToString()=True)cb16Display.Checked=true;elsecb16Display.Checked=false;#endregion#region初始化按16进制发送状态if(ht.ContainsKey(cb16S

27、end)&htcb16Send.ToString()=True)cb16Send.Checked=true;elsecb16Send.Checked=false;#endregion#region初始化发送区文本if(ht.ContainsKey(tbSendData16)&ht.ContainsKey(tbSendDataStr)tbSendData16=httbSendData16.ToString();tbSendDataStr=httbSendDataStr.ToString();if(cb16Send.Checked)tbSendData.Text=httbSendData16.To

28、String();elsetbSendData.Text=httbSendDataStr.ToString();#endregiontbSendData.Focus();/显示当前时间privatevoidtimer1_Tick(objectsender,EventArgse)toolStripStatusLabel3.Text=DateTime.Now.ToString();精彩文档实用标准文案/点击打开串口按钮privatevoidbtnOpenCom_Click(objectsender,EventArgse)if(!sp.IsOpen)/串口没有打开时if(!isSetProperty

29、)/串口未设置则设置串口属性SetPortProperty();isSetProperty=true;trysp.Open();btnOpenCom.Text=关闭串口;DisplayPortState(PortState.打开);catch(Exception)/串口打开失败后,串口属性设置标志位设为falseisSetProperty=false;MessageBox.Show(串口无效或已被占用!,错误提示);else/串口已经打开trysp.Close();isSetProperty=false;btnOpenCom.Text=打开串口;DisplayPortState(PortSta

30、te.关闭);catch(Exception)MessageBox.Show(关闭串口时发生错误,错误提示);/发送串口数据privatevoidbtnSend_Click(objectsender,EventArgse)if(tbSendData.Text.Trim()=)/检测发送数据是否为空MessageBox.Show(请输入要发送的数据!,错误提示);return;if(sp.IsOpen)DataSend();精彩文档实用标准文案elseMessageBox.Show(串口未打开!,错误提示);/点击端口号选择下拉框按钮privatevoidcbxCOMPort_SelectedI

31、ndexChanged(objectsender,EventArgse)AgainOpenPort();/点击波特率选择下拉框按钮privatevoidcbxBaudRate_SelectedIndexChanged(objectsender,EventArgse)AgainOpenPort();/点击数据位选择下拉框按钮privatevoidcbxDataBits_SelectedIndexChanged(objectsender,EventArgse)AgainOpenPort();/点击停止位选择下拉框按钮privatevoidcbxStopBits_SelectedIndexChang

32、ed(objectsender,EventArgse)AgainOpenPort();/点击校验位选择下拉框按钮privatevoidcbxParity_SelectedIndexChanged(objectsender,EventArgse)AgainOpenPort();/点击数据接收区清空按钮privatevoidbtnClearReceived_Click(objectsender,EventArgse)receivedDatas.Clear();tbReceivedData.Text=;/点击是否按16进制显示接收数据privatevoidcb16Display_CheckedCha

33、nged(objectsender,EventArgse)if(cb16Display.Checked)精彩文档实用标准文案tbReceivedData.Text=Methods.ByteTo16Str(receivedDatas.ToArray();elsetbReceivedData.Text=Encoding.Default.GetString(receivedDatas.ToArray();/点击是否按16进制发送数据privatevoidcb16Send_CheckedChanged(objectsender,EventArgse)if(cb16Send.Checked)tbSend

34、Data.Text=tbSendData16;elsetbSendData.Text=tbSendDataStr;/发送文本框键盘按键检测privatevoidtbSendData_KeyPress(objectsender,KeyPressEventArgse)if(cb16Send.Checked)/正则匹配stringpattern=0-9a-fA-F|b;/b:退格键Matchm=Regex.Match(e.KeyChar.ToString(),pattern);if(m.Success)if(e.KeyChar!=b)if(tbSendData.Text.Length%3=2)tbS

35、endData.Text+=;tbSendData.SelectionStart=tbSendData.Text.Length;e.KeyChar=Convert.ToChar(e.KeyChar.ToString().ToUpper();e.Handled=false;elsee.Handled=true;elsee.Handled=false;/点击清空发送内容privatevoidbtnClearSend_Click(objectsender,EventArgse)tbSendData.Text=;if(cb16Send.Checked)精彩文档实用标准文案tbSendData16=;e

36、lsetbSendDataStr=;/点击清空计数器数据privatevoidbtnClearCount_Click(objectsender,EventArgse)tbReceivedCount.Text=0;tbSendCount.Text=0;/点击是否设置自动发送privatevoidcbAutomaticSend_CheckedChanged(objectsender,EventArgse)if(cbAutomaticSend.Checked)timer2.Enabled=true;timer2.Interval=Convert.ToInt32(tbSpaceTime.Text);e

37、lsetimer2.Enabled=false;/自动发送时间文本框键盘按键检测privatevoidtbSpaceTime_KeyPress(objectsender,KeyPressEventArgse)/正则匹配stringpattern=0-9|b;Matchm=Regex.Match(e.KeyChar.ToString(),pattern);if(m.Success)timer2.Interval=Convert.ToInt32(tbSpaceTime.Text);e.Handled=false;elsee.Handled=true;/串口显示状态privatevoidtimer2

38、_Tick(objectsender,EventArgse)if(sp.IsOpen)DataSend();elsetimer2.Enabled=false;cbAutomaticSend.Checked=false;MessageBox.Show(串口未打开!,错误提示);精彩文档实用标准文案return;if(tbSendData.Text.Trim()=)/检测发送数据是否为空timer2.Enabled=false;cbAutomaticSend.Checked=false;MessageBox.Show(请输入要发送的数据!,错误提示);return;/关闭窗口时出发的事件priva

39、tevoidForm1_FormClosed(objectsender,FormClosedEventArgse)tryusing(StreamWritersw=newStreamWriter(path,false)sw.WriteLine(cbxCOMPort=+cbxCOMPort.Text);sw.WriteLine(cbxBaudRate=+cbxBaudRate.Text);sw.WriteLine(cbxDataBits=+cbxDataBits.Text);sw.WriteLine(cbxStopBits=+cbxStopBits.Text);sw.WriteLine(cbxParity=+cbxParity.Text);sw.WriteLine(cb16Display=+cb16Display.Checked.ToString();sw.WriteLine(tbSpaceTime=+tbSpaceTime.Text);sw.WriteLine(cb16Send=+cb16Send.Checked.ToString();sw.WriteLine(

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 科普知识


经营许可证编号:宁ICP备18001539号-1