c#上位機(jī)串口通信助手源代碼詳解_第1頁
c#上位機(jī)串口通信助手源代碼詳解_第2頁
c#上位機(jī)串口通信助手源代碼詳解_第3頁
c#上位機(jī)串口通信助手源代碼詳解_第4頁
c#上位機(jī)串口通信助手源代碼詳解_第5頁
免費(fèi)預(yù)覽已結(jié)束,剩余1頁可下載查看

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1、精心整理C#上位機(jī)串口通信助手源代碼實(shí)例詳解一、功能1軟件翻開時(shí),自動(dòng)檢測有效COM端口2軟件翻開時(shí),自動(dòng)復(fù)原到上次關(guān)閉時(shí)的狀態(tài)3不必關(guān)閉串口,即可直接進(jìn)行更改初始化設(shè)置內(nèi)容(串口號、波特率、數(shù)據(jù)位、停止位、校驗(yàn)位), 可按更改后的信息自動(dòng)將串口重新翻開4可統(tǒng)計(jì)接收字節(jié)和發(fā)送字節(jié)的個(gè)數(shù)5接收數(shù)據(jù)可按16進(jìn)制數(shù)據(jù)和非16進(jìn)制數(shù)據(jù)進(jìn)行整體轉(zhuǎn)換6可將接收到數(shù)據(jù)進(jìn)行保存7可設(shè)置自動(dòng)發(fā)送,發(fā)送時(shí)間可進(jìn)行實(shí)時(shí)更改8可按字符串、16進(jìn)制字節(jié)、文件方式進(jìn)行發(fā)送,字符串和16進(jìn)制字節(jié)可分別進(jìn)行存儲(chǔ),內(nèi)容互不干 擾9按16進(jìn)制發(fā)送時(shí),可自動(dòng)校驗(yàn)格式,不會(huì)輸錯(cuò)10可清空發(fā)送或接收區(qū)域的數(shù)據(jù)二、使用工具VisualS

2、tudio2015三、程序詳解1界面創(chuàng)立用winform創(chuàng)立如圖1所示界面,控件名字分別為: 端口號:cbxCOMPort 波特率:cbxBaudRate數(shù)據(jù)位:cbxDataBits 停止位:cbxStopBits校驗(yàn)位:Iabel5翻開串口按鈕:btnOpenCom發(fā)送(byte ) : tbSendCount 接收(byte ) : tbReceivedCount 清空計(jì)數(shù)按鈕:btnClearCount按16進(jìn)制顯示:cbl6Display 接收區(qū)清空內(nèi)容按鈕:btnClearReceived保存數(shù)據(jù)按鈕:btnSaveFile 接收數(shù)據(jù)框:tbReceivedData發(fā)送數(shù)據(jù)框:tb

3、SendData 自動(dòng)發(fā)送:cbAutomaticSend 間隔時(shí)間:tbSpaceTime按16進(jìn)制發(fā)送:cbl6Send發(fā)送區(qū)清空內(nèi)容按鈕:btnClearSend 讀入文件按鈕:btnReadFile發(fā)送按鈕:btnSend2創(chuàng)立一個(gè)方法類按Ctrl+shift+A快捷鍵創(chuàng)立一個(gè)類,名字叫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;) )點(diǎn)擊清空發(fā)送內(nèi)容privatevoidbtnClearSend Click(objectsender, IwentArgse) ( tbSendData. Text=; if (cbl6Send. Checked) tbSendDatal6二; elsetbSendDataStr二; )點(diǎn)擊清空計(jì)數(shù)器數(shù)據(jù)privatevoidbtnClearCount Click(objectsender, EventArgse) (tbReceive

5、dCount. Text二; tbSendCount. Text二; )點(diǎn)擊是否設(shè)置自動(dòng)發(fā)送privatevoidcbAutomaticSend CheckedChanged(objectsender, KventArgse) (if (cbAutomaticSend. Checked) (timer2.Enabled=true;timer2. Interval=Convert. Tolnt32 (tbSpaceTime.Text);) else ( timer2. Enabled=false;) )自動(dòng)發(fā)送時(shí)間文本框鍵盤按鍵檢測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;) )串口顯示狀態(tài)privatevoidtimer2 Tick(objectsender, EventArgse) ( -if (sp. IsOpen)DataSend ();) else ( timer2. Enabled=f

7、alse; cbAutomaticSend. Checked=false;MessageBox. Show(串口未翻開!,錯(cuò)誤提示); return;)if ) 檢測發(fā)送數(shù)據(jù)是否為空 (timer2. Enabled=false;cbAutomaticSend. Checked=false;MessageBox. Show (請輸入要發(fā)送的數(shù)據(jù)!,錯(cuò)誤提示); return;) )關(guān)閉窗口時(shí)出發(fā)的事件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)發(fā)送文本框按鍵抬起時(shí)出發(fā)的事件privatevoidtbSendData KeyUp(objectsender, KeyEventArgse) ( if(cbl6Send. Checked)()else tbSendDataStr=tbSendData. Text;點(diǎn)擊讀入文件按鈕privatevoid

10、btnReadFile_Click(objectsender, liventArgse) ( openFileDialogl. Fil ter 二所有文件(*. *) | *. *;文件篩選器的設(shè)定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 ;點(diǎn)擊保存數(shù)據(jù)按鈕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#技術(shù)交流群(), 附加信息為我以下載此文檔,進(jìn)群后找群主索要源代碼或進(jìn)行技 術(shù)交流。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進(jìn)制字符串轉(zhuǎn)換為byte字符數(shù)組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數(shù)組以16進(jìn)制形式轉(zhuǎn)字符串publicstaticstringByteTo16Str(bytebytes) (stringrecData=null; 創(chuàng)立接收數(shù)據(jù)的字符串foreach(byteoutByteinbytes) 將字節(jié)數(shù)組以16進(jìn)制形式遍歷到一個(gè)字符串內(nèi) (recData+=outByte. ToString (X2)+“;)returnrecData;)/16進(jìn)制字符串轉(zhuǎn)換字符串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; 串 口屬性設(shè)置標(biāo)志位 privateenumPortState聲明接口顯示狀態(tài),枚舉型 (翻開,關(guān)閉 )stringpath=AppI)oinain. CurrentDomain. Basel)irectory+Z,confing. ini;聲明配置文件路徑 s

18、tringtbSendDataStr=,/,; 發(fā)送窗口字符串存儲(chǔ)stringtbSendI)atal6 二;發(fā)送窗口 16 進(jìn)制存儲(chǔ)ListreceivedDatas=newIJ st () ;/接收數(shù)據(jù)泛型數(shù)組 接收串口數(shù)據(jù)privatevoidsp DataReceived(objectsender, SerialDataReceivedEventArgse) ( byteReceivedData=newbyte sp. BytesToRead; 創(chuàng)立接收字節(jié)數(shù)組sp. Read (ReceivedData, 0, ReceivedData. Length); 讀取所接收到的數(shù)據(jù) 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 ();丟棄接收緩沖區(qū)數(shù)據(jù) )發(fā)送串口數(shù)據(jù) 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

21、SendDataStr);tbSendCount. Text= (Convert.Tolnt32 (tbSendCount. Text)+tbSendDataStr. Length). ToString();catch (Ixceptionex)MessageBox return;) )設(shè)置串口屬性privatevoidSetPortProperty() (設(shè)置串口名sp. BaudRate=Convert設(shè)置波特率switch 設(shè)置停止位 (casel:sp.StopBits=StopBits. One;break;case,zl. 5: sp. StopBits=StopBits. One

22、PointFive; break;case2:sp.StopBits=StopBits. Two;break;default:sp. StopBits=StopBits. None;break; )sp. DataBits=Convert設(shè)置數(shù)據(jù)位swi t ch 設(shè)置奇偶校驗(yàn)位 (case無:sp. Parity=Pari ty. None; break;case奇校驗(yàn):sp. Parity=Parity. Odd;break;case”偶校驗(yàn):sp. Parity=Parity. Even;break;default:sp. Parity=Parity. None;break; )sp.

23、ReadTimeout=5000; 設(shè)置超時(shí)時(shí)間為5sControl. CheckFor11legalCrossThreadCal1s=false; 這個(gè)類中我們不檢查跨線程的調(diào)用是否合法(因?yàn)?net2. 0以后加強(qiáng) 了平安機(jī)制不允許在winform中直接跨線程訪問控件的屬性)定義DataReceived事件的委托,當(dāng)串口收到數(shù)據(jù)后出發(fā)事件sp. DataReceived+=newSerialDataReceivedEventHandler (sp DataReceived);) 設(shè)置端口顯示狀態(tài)pri vatevoi dl)i spl ayPortState (lrtStat eportS

24、tate) (toolStripStatusLabel 1. Text二cbxCOMPort. Text+端口處于+portState+狀態(tài)z,+cbxBaudRate. Text+zz/,+cbxDataBits. Text+cbxStopBits. Text+cbxParity. Text; )重新翻開串口privatevoidAgainOpenPort() (if (sp. IsOpen) (try ( sp. Close ();SetPortProperty(); isSetProperty=true; sp. Open ();)catch(Exception) (isSetPrope

25、rty=false;btnOpenCom. Text二翻開串口;DisplayPortState (PortState.關(guān)閉);MessageBox. Show(串口無效或已被占用!,錯(cuò)誤提示);精心整理return;)DisplayPortState (PortState.翻開);)else(DisplayPortState (PortState.關(guān)閉);)publicForml()(InitializeComponent();)軟件啟動(dòng)時(shí)加載事件privatevoidForml Load(objectsender,EventArgse) ( .Sregi on加載配置文件I lash ta

26、b 1 eht=newl lash tab 1 e ();if (File. Exists(path)(try(stringmyline=zz,/;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)#endregion#regi on設(shè)置窗口為

27、固定大小且不可最大化this.MaximumSize=this. Size;this.MinimumSize=this. Size;this. MaximizeBox=false;#endregion去egion列出常用的波特率1200);2400);4800);9600);19200);38400);43000);56000);57600);115200);if(ht. ContainsKey(cbxBaudRate)/zcbxBaudRatez/. ToString();elsecbxBaudRate. Selectedlndex=3;cbxBaudRate. DropDownStyle=

28、ComboBoxStyle. DropDownList;#endregion#region列出停止位1);L5);2);if(ht. ContainsKey(cbxStopBits)“cbxStopBits.ToStringO);elsecbxStopBits. SelectedIndex=O;cbxStopBits. DropDownSty1e=ComboBoxSty1e. DropDownList;Scndrcgion#region列出數(shù)據(jù)位8);7);6);5);if(ht. ContainsKey(cbxDataBits)“cbxDataBits1.ToString();elsecbx

29、DataBits. SelectedIndex=O;cbxDataBits. I)ropDownStyle=ComboBoxStyIe. DropDownList;Sendregion#region列出奇偶校驗(yàn)位無);奇校驗(yàn));偶校驗(yàn));if (ht. ContainsKey(cbxParity)cbxParity. ToStringO);elsecbxParity. SelectedIndex=O;cbxParity.DropDownStyle=ComboBoxStyle. DropDownList;#endregion#regionC0M 口重新加載清除當(dāng)前串口號中的所有串口名稱Metho

30、ds. ActivePorts ();if (ht. ContainsKey (z/cbxCOMPort,zcbxCOMPortz,. ToString () /zcbxCOMPortz/. ToString ();elsecbxCOMPort. SelectedIndex=O;cbxCOMPort. DropDownStyle=ComboBoxStyle. DropDownList;#endregionr eg i on初始化計(jì)數(shù)器tbSendCount. Text二0;tbSendCount. ReadOnly=true;tbReceivedCount. Text二0;tbReceived

31、Count. Readonly=true;Sendregionr eg ion初始化當(dāng)前時(shí)間toolstripStatusLabel3. Text=I)ateTime. Now. ToStringO ;#endregionr eg i on初始化串口狀態(tài)toolStripStatusLabell. ForeColor=Color. Blue;精心整理if(!isSetProperty) 串口未設(shè)置那么設(shè)置串口屬性 SetPortProperty();isSetProperty=true;) try ( sp. Open ();btnOpenCom. Text二關(guān)閉串口;DisplayPortS

32、tate (PortState.翻開);)catch(Exception) (串口翻開失敗后,串口屬性設(shè)置標(biāo)志位設(shè)為falseisSetProperty=false;MessageBox. Show(串口無效或已被占用!,錯(cuò)誤提示);)#endregion#region初始化間隔時(shí)間if(ht. ContainsKey(tbSpaceTime)tbSpaceTime. Text=ht tbSpaceTime ToStringO ;elsetbSpaceTime. Text=1000;Sendregion#r eg i on初始化按16進(jìn)制顯示狀態(tài)if (ht. ContainsKey (cbl

33、6Display)&ht cbl6Display. ToString0 =,True,/) cbl6Display. Checked=true;elsecbl6Display. Checked=false;Sendregion#region初始化按16進(jìn)制發(fā)送狀態(tài)if (ht. ContainsKey (cbl6Send)&ht cbl6Send. ToStringO二二True) cbl6Send. Checked=true;elsecbl6Send. Checked=false;#endregion#region初始化發(fā)送區(qū)文本if (ht. ContainsKey (tbSendData

34、l6)&ht. ContainsKey (tbSendDataStr) (tbSendDatal6=ht z/tbSendDatal6,J. ToStringO ;tbSendDataStr=htz,tbSendDataStr,l. ToStringO ;if(cbl6Send. Checked)tbScndData. Text=httbScndDatal61. ToStringO ; elsetbSendData. Text=httbScndDataStr ToStringO ; )SendregiontbSendData. Focus ();)顯示當(dāng)前時(shí)間privatevoidtimeri

35、 Tick (objectsender, EventArgse) (toolStripStatusLabel3. Text=I)atcTimc. Now. ToStringO ;)點(diǎn)擊翻開串口按鈕privatevoidbtnOpenCom Click(objectsender, EventArgse)if (!sp. IsOpen)串口沒有翻開時(shí) (if(!i sSetProper ty) 串口未設(shè)置那么設(shè)置串口屬性 (SetPortProperty();i sSetProperty=true;) try ( sp. Open ();btnOpenCom. Text二關(guān)閉串口;DisplayP

36、ortState (PortState.翻開);)catch(Exception) (串口翻開失敗后,串口屬性設(shè)置標(biāo)志位設(shè)為false isSetProperty=false;MessageBox. Show(串口無效或已被占用!,錯(cuò)誤提示); ) )else 串口已經(jīng)翻開( try(sp. Close ();isSetProperty=false;btnOpenCom. Text翻開串口;DisplayPortState (PortState.關(guān)閉);)catch(Exception) (MessageBox. Show(關(guān)閉串口時(shí)發(fā)生錯(cuò)誤,錯(cuò)誤提示);) )發(fā)送串口數(shù)據(jù)privatevoidbtnSend Click(objectsender, EventArgse) (if ) 檢測發(fā)送數(shù)據(jù)是否為空 (MessageBox. Show (請輸入要發(fā)送的數(shù)據(jù)!,錯(cuò)誤提示); return;)if(sp. IsOpen)(DataSend ();) else (MessageBox. Show

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔