c#上位机串口通信助手源代码详解.docx
《c#上位机串口通信助手源代码详解.docx》由会员分享,可在线阅读,更多相关《c#上位机串口通信助手源代码详解.docx(6页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、精心整理C#上位机串口通信助手源代码实例详解一、功能1软件翻开时,自动检测有效COM端口2软件翻开时,自动复原到上次关闭时的状态3不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位), 可按更改后的信息自动将串口重新翻开4可统计接收字节和发送字节的个数5接收数据可按16进制数据和非16进制数据进行整体转换6可将接收到数据进行保存7可设置自动发送,发送时间可进行实时更改8可按字符串、16进制字节、文件方式进行发送,字符串和16进制字节可分别进行存储,内容互不干 扰9按16进制发送时,可自动校验格式,不会输错10可清空发送或接收区域的数据二、使用工具VisualS
2、tudio2015三、程序详解1界面创立用winform创立如图1所示界面,控件名字分别为: 端口号:cbxCOMPort 波特率:cbxBaudRate数据位:cbxDataBits 停止位:cbxStopBits校验位:Iabel5翻开串口按钮:btnOpenCom发送(byte ) : tbSendCount 接收(byte ) : tbReceivedCount 清空计数按钮:btnClearCount按16进制显示:cbl6Display 接收区清空内容按钮:btnClearReceived保存数据按钮:btnSaveFile 接收数据框:tbReceivedData发送数据框:tb
3、SendData 自动发送:cbAutomaticSend 间隔时间:tbSpaceTime按16进制发送:cbl6Send发送区清空内容按钮:btnClearSend 读入文件按钮:btnReadFile发送按钮:btnSend2创立一个方法类按Ctrl+shift+A快捷键创立一个类,名字叫Methods ,代码为:usingSystem;usingSystem. Collections; using usingusingSystem. Linq;usingSystem. Text;usingnamespace 串 口助手 sddif (e. KeyChar!=b) tbSendData.
4、 Text+=;) ) e.Handled=false;) else e.Handled=true;) ) else ( e.Handled=false;) )点击清空发送内容privatevoidbtnClearSend Click(objectsender, IwentArgse) ( tbSendData. Text=; if (cbl6Send. Checked) tbSendDatal6二; elsetbSendDataStr二; )点击清空计数器数据privatevoidbtnClearCount Click(objectsender, EventArgse) (tbReceive
5、dCount. Text二; tbSendCount. Text二; )点击是否设置自动发送privatevoidcbAutomaticSend CheckedChanged(objectsender, KventArgse) (if (cbAutomaticSend. Checked) (timer2.Enabled=true;timer2. Interval=Convert. Tolnt32 (tbSpaceTime.Text);) else ( timer2. Enabled=false;) )自动发送时间文本框键盘按键检测privatevoidtbSpaceTime KeyPress(
6、objectsender, KeyPressEvontArgse) ( 正那么匹配stringpattern=0-9|b;Matchm=Regex if (m. Success) ( timer2. Interval=Convert. Tolnt32(tbSpaceTime. Text); e.Handled=false;else精心整理(e.Handled=true;) )串口显示状态privatevoidtimer2 Tick(objectsender, EventArgse) ( -if (sp. IsOpen)DataSend ();) else ( timer2. Enabled=f
7、alse; cbAutomaticSend. Checked=false;MessageBox. Show(串口未翻开!,错误提示); return;)if ) 检测发送数据是否为空 (timer2. Enabled=false;cbAutomaticSend. Checked=false;MessageBox. Show (请输入要发送的数据!,错误提示); return;) )关闭窗口时出发的事件privatevoidForml FormClosed(objectsender, FormClosedEventArgse) ( try (using(StreamWritersw=newStr
8、eamWriter(path, false) (sw. WriteLine (z/cbxCOMPort=,+cbxCOMPort. Text);sw. WriteLine (zzcbxBaudRate=,z+cbxBaudRate. Text);sw. WriteLine (zzcbxDataBits=z/+cbxDataBits. Text);sw.WriteLine (cbxStopBits=+cbxStopBits. Text);sw. WriteLine (zzcbxParity=/z+cbxParity. Text);sw. WriteLine (zztbSpaceTime=/z+t
9、bSpaceTime. Text);sw. WriteLine (zztbSendDataStr=,z+tbSendDataStr);sw. WriteLine (,ztbSendDatal6=,+tbSendDatal6);sp. Close ();) ) catch(Exceptionex)发送文本框按键抬起时出发的事件privatevoidtbSendData KeyUp(objectsender, KeyEventArgse) ( if(cbl6Send. Checked)()else tbSendDataStr=tbSendData. Text;点击读入文件按钮privatevoid
10、btnReadFile_Click(objectsender, liventArgse) ( openFileDialogl. Fil ter 二所有文件(*. *) | *. *;文件筛选器的设定openFileDialogl. Filterlndex=l;openFileDialogl. Title=选择文件;openFileDialogl. FileName=;openFileDialogl. ShowHelp=true;if (openFileDialogl. ShowDialog()=DialogResult. OK) using (Fi leStreamf s=newl?i leS
11、tream (openFileDialogl. Fil eName, Fil eMode. Open) (bytebufferByte=newbytefs. Length;fs. Read (bufferByte, 0, Convert. Tolnt32 (fs. Length);sp.Write(bufferByte, 0, bufferByte. Length);tbSendCount. Text= (Convert. Tolnt32 (tbSendCount. Text) +bufferByte. Length). ToStringO ;点击保存数据按钮privatevoidbtnSav
12、eFile Click(objectsender, IwentArgse) ( saveFileDialogl. Fil ter 二所有文件(札 *) | *. *;if (saveFileDialogl. ShowDialog()=DialogResult. OK) (stringfName=saveFileDialogl. FileName;using(FileStreamfs=File. Open(fName, FileMode. Append) (fs.Write(receivedDatas. ToArray(), 0, receivedDatas. Count);)需要源代码或有疑问
13、的C#爰好者们,欢迎加入C#技术交流群(), 附加信息为我以下载此文档,进群后找群主索要源代码或进行技 术交流。classMethods获取有效的COM 口publicstaticstringActivePorts() (ArrayLi stactivePorts=newArrayLi st();foreach(stringpnameinSeri al Port. GetPortNames() (activePorts. Add(Convert. Tolnt32(pname. Substring(3);)activePorts. Sort ();stringmystr=newstringact
14、ivePorts. Count;inti=0;foreach(intnuminactivePorts)(mystri+=C0M+num. ToStringO;)returnmystr;)16进制字符串转换为byte字符数组publicstaticByte_16strToHex(stringstrValues)(stringhexValuesSplit=strValues. Split ();hexValues=newBytehexValuesSplit. Length;Console. WriteLine(hexValuesSplit. Length);for(inti=0;ihexValue
15、sSplit. Length;i+)(hexValuesi=Convert. ToByte(hexValuesSpliti, 16);)returnhexValues;)byte数组以16进制形式转字符串publicstaticstringByteTo16Str(bytebytes) (stringrecData=null; 创立接收数据的字符串foreach(byteoutByteinbytes) 将字节数组以16进制形式遍历到一个字符串内 (recData+=outByte. ToString (X2)+“;)returnrecData;)/16进制字符串转换字符串publicstatic
16、string_16strToStr(string_16str) ( 一stringoutStr=null;byte 口 streamByte=_16strToIIex (_16str);outStr=Encoding. Default. GetString(streamByte);returnoutStr;)2Forml. cs的代码为:usingSystem;usingusingSystem.ComponentModel;usingSystem. Data;usingSystem. Drawing;using精心整理usingSystem. Linq; usingSystem. Text;
17、using using usingusingSystem. 10;usingSystem. Collections; namespace 串 口助手 sdd publicpartialclassForml:Form (声明变量SerialPortsp=newSerialPort();bool i sSetProperty=false; 串 口属性设置标志位 privateenumPortState声明接口显示状态,枚举型 (翻开,关闭 )stringpath=AppI)oinain. CurrentDomain. Basel)irectory+Z,confing. ini;声明配置文件路径 s
18、tringtbSendDataStr=,/,; 发送窗口字符串存储stringtbSendI)atal6 二;发送窗口 16 进制存储ListreceivedDatas=newIJ st () ;/接收数据泛型数组 接收串口数据privatevoidsp DataReceived(objectsender, SerialDataReceivedEventArgse) ( byteReceivedData=newbyte sp. BytesToRead; 创立接收字节数组sp. Read (ReceivedData, 0, ReceivedData. Length); 读取所接收到的数据 rec
19、eivedDatas. AddRange(ReceivedData);tbReceivedCount. Text=(Convert. Tolnt32(tbReceivedCount. Text)+ReceivedData. Length). ToString(); if(cbl6Display. Checked)tbReceivedData. Text=Methods, ByteTol6Str(receivedDatas. ToArray(); elsetbReceivedData. Text=Encoding. Default. GetString(receivedDatas. ToArra
20、y(); sp. DiscardlnBuffer ();丢弃接收缓冲区数据 )发送串口数据 privatevoidDataSend() ( try (if (cb!6Send. Checked) (bytehexBytes=Methods. _16strToHex(tbSendDatal6);sp. Write (hexBytes, 0, hexBytes. Length);tbSendCount. Text= (Convert. Tolnt32 (tbSendCount. Text)+hexBytes. Length). ToString(); ) else (sp.WriteLine(tb
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- c# 上位 串口 通信 助手 源代码 详解
限制150内