C#和232串口通信方法(SerialPort控件)_第1頁
C#和232串口通信方法(SerialPort控件)_第2頁
C#和232串口通信方法(SerialPort控件)_第3頁
C#和232串口通信方法(SerialPort控件)_第4頁
C#和232串口通信方法(SerialPort控件)_第5頁
已閱讀5頁,還剩34頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡介

1、本例程主要講解使用c#,實(shí)現(xiàn)與232串口通信。達(dá)到采集串口數(shù)據(jù),監(jiān)控,可視化 處理等。一 .概述在Visual Studio 6.0中編寫串口通訊程序,一般都使用Microsoft Communication Control (簡稱 MSComm )的通訊控件,只要通 過對此控件的屬性和事件進(jìn)行相應(yīng)編程操作,就可以輕松地實(shí)現(xiàn)串口通訊。但在 Microsoft.Net技術(shù)廣泛應(yīng)用的今天,Visual Studio.Net沒有將此控件加入控件庫, 所以人們采用了許多方法在Visual Studio.Net來編寫串口通訊程序:第一種方法是通過采用Visual Studio 6.0中原來的MSComm

2、控件這是最簡 單的, 最方便的方法,但需要注冊;第二種方法是采用微軟在.NET推出了一個串口控件,基于.NET的P/lnvoke調(diào)用方法實(shí)現(xiàn);第三種方法是自己用API寫串口 通信,雖然難度高,但可以方便實(shí)現(xiàn)自己想要的各種功能?,F(xiàn)在微軟推出了最新版本的Visual Studio 2005開發(fā)工具,可以不再采用第三方控件的方法來設(shè)計串口通訊程序。NET Framework 2.0 類庫包含了 SerialPort類,方便地實(shí)現(xiàn)了所需要串口通訊的多種功能,為了使MSComm編程方法快速轉(zhuǎn)換到以SerialPort類為核心的串口通訊的設(shè)計方法,本文著重討論了 Visual Studio 6.0的MSC

3、omm控件和SerialPort類設(shè)計方法的異同 點(diǎn)。SerialPort常用屬性、方法和事件1 .命名空間System.lO.Ports命名空間包含了控制串口重要的SerialPort類,該類提供了同步I/O和事件驅(qū)動的I/O、對管腳和中斷狀態(tài)的訪問以及對串行驅(qū)動 程序?qū)?性的訪問,所以在程序代碼起始位置需加入Usi ng System.lO.Ports。2 ,串口的通訊參數(shù)串口通訊最常用的參數(shù)就是通訊端口號及通訊格式(波特率、數(shù)據(jù)位、停止位和校驗(yàn)位),在MSComm中相關(guān)的屬性是CommPort和SettingsSerialPort類與MSComm有一些區(qū)別:a.通訊端口號COMPortN

4、ame屬性獲取或設(shè)置通信端口,包括但不限于所有可用的端口,請注意該屬性返回類型為String ,不是Mscomm.CommPort的short類型。通常情況下,PortName正常返回的值為COM1、COM2,SerialPort類最大支持 的端口數(shù)突破了 CommPort控件中CommPort屬性不能超過16的限止,大大方便了用戶串口設(shè)備的配置。b.通訊格式SerialPort 類對分別用BaudRate、PaHty、DataB網(wǎng)、StopB屬性設(shè)置通訊格式中的波特率、數(shù)據(jù)位、停止位和校驗(yàn)位,其中PaHty和StopBits分別是枚舉類型Parity、StopBits , Parity類型中

5、枚舉了 Odd(奇)、 Even(偶)、Mark、None、Space,Parity 枚舉了 None、One、OnePointFiveTwo oSerialPort類提供了七個重載的構(gòu)造函數(shù),既可以對已經(jīng)實(shí)例化的SerialPort對象設(shè)置上述相關(guān)屬性的值,也可以使用指定的端口名稱、波特率和奇偶校驗(yàn)位數(shù)據(jù)位和停止位直接初始化SerialPort類的新實(shí)例。3 .串口的打開和關(guān)閉SerialPort 類沒有采用 MSComm.PortOpen=True/False設(shè)置屬性值打開關(guān)閉串口,相應(yīng)的是調(diào)用類的Open()和Close。方法。4 .數(shù)據(jù)的發(fā)送和讀取Serial類調(diào)用重載的Write和W

6、riteLine方法發(fā)送數(shù)據(jù),其中WriteLine可發(fā)送 字符串并在字符串末尾加入換行符,讀取串口緩沖區(qū)的方法有許多,其中除了 ReadExisting和ReadTo,其余的方法都是同步調(diào)用,線程被阻塞直到緩沖區(qū)有相應(yīng)的數(shù)據(jù)或大于ReadTimeOut屬性設(shè)定的時間值后,引發(fā)ReadExisti ng異常。5 . DataReceived 事件 該事件類似于MSComm控件中的On Comm事件,DataReceived事件 在接收到了 ReceivedBytesThreshold設(shè)置的字符個數(shù)或接收到了文件結(jié)束字符并將其放入了輸入緩沖區(qū)時被觸發(fā)。其中ReceivedBytesThresho

7、ld相當(dāng)于MSComm控件的Rthreshold屬性,該事件的用法與MsComm控件的On Comm 事件在 CommEve nt 為 comEvSe nd 和 comEvEof 時是一致三SerialPort的使用對于熟悉MSComm控件的程序設(shè)計者,SerialPort類是相當(dāng)容易上手 的。在 進(jìn)行串口通訊時,一般的流程是設(shè)置通訊端口號及波特率、數(shù)據(jù)位、停止位和校驗(yàn) 位,再打開端口連接,發(fā)送數(shù)據(jù),接收數(shù)據(jù),最后關(guān)閉端口連接這樣幾個步驟。數(shù)據(jù)接收的設(shè)計方法在這里比較重要,采用輪詢的方法比較浪費(fèi)時間,在 Visual Basic中的延時方法中一般會調(diào)用API并用DOEvents方法來處理,但

8、程序 不易控制,建議采用DataReceived事件觸發(fā)的方法,合理的設(shè)置ReceivedBytesThreshold 的值,若接收的是定長的數(shù)據(jù),則將 ReceivedBytesThreshold設(shè)為接收數(shù)據(jù)的長度,若接收數(shù)據(jù)的結(jié)尾是固定的字符或字符串則可采用ReadTo的方法或在DataReceived事件中判斷接收的 字符 是否滿足條件。SerialPort類讀取數(shù)據(jù)的許多方法是同步阻塞調(diào)用,盡量避免在主線程中調(diào) 用,可以使用異步處理或線程間處理調(diào)用這些讀取數(shù)據(jù)的方法。由于DataReceived事件在輔線程被引發(fā),當(dāng)收到完整的一條數(shù)據(jù),返回主線 程處理或在窗體上顯示時,請注意跨線程的處

9、理,C#可采用控件異步委托的方法Control.Beginlnvoke及同步委托的方法Invoke。四.結(jié)束語在.NET平臺下熟練使用SerialPort類,可以很好地開發(fā)出串口通訊類程 序, 對于過去使用MSComm控件設(shè)計了一些通訊程序,也可以將MSComm 控件替換為SerialPort類,當(dāng)然為了避免對以前的項目做大的改動,可以使用 SerialPort類設(shè)計一些與MSComm控件具有相同接口的類,在今后工業(yè)控制 中, SerialPort類將廣泛地應(yīng)用于串口通訊程序的設(shè)計中, 發(fā)揮著與MSComm 控件一樣的作用。C# SerialPort運(yùn)行方式SerialPort中串口數(shù)據(jù)的讀取

10、與寫入有較大的不同。由于串口不知道數(shù)據(jù)何時到達(dá),因此有兩種方法可以實(shí) 現(xiàn)串口數(shù)據(jù)的讀取。一、線程實(shí)時讀串口;二、事件觸發(fā)方式實(shí)現(xiàn)。由于線程實(shí)時讀串口的效率不是十分高效,因此比較好的方法是事件觸發(fā)的方式。在SerialPort類中有DataReceived事件,當(dāng)串口的讀緩存有數(shù)據(jù)到達(dá)時則觸發(fā)DataReceived事件,其中SerialPort.ReceivedBytesThreshold屬性決定了當(dāng)串口讀緩存中數(shù)據(jù)多少個時才觸發(fā)DataReceived事件, 默認(rèn)為1。 另外,SerialPort.DataReceived事件運(yùn)行比較特殊,其運(yùn)行在輔線程,不能與主線程中的顯示數(shù)據(jù)控件直接進(jìn)行

11、數(shù)據(jù)傳輸,必須用間接的方式實(shí)現(xiàn)。如下:SerialPort spSe nd; /spSe nd,spReceive用虛擬串口連接,它們之間可以相互傳輸數(shù)據(jù)。spSe nd發(fā)送數(shù)據(jù)SerialPort spReceive; /spReceive 接受數(shù)據(jù)TextBox txtSe nd; / 發(fā)送區(qū)TextBox txtReceive; / 接受區(qū)Button btn Se nd;/數(shù)據(jù)發(fā)送按鈕delegate void Han die In terfaceUpdateDelegate(stri ng text); / 委托,此為重點(diǎn) Han die In terfaceUpdateDelega

12、te in terfaceUpdateHa ndle;public void In itClie nt() /窗體控件已在初始化( in terfaceUpdateHa ndle = new Han die In terfaceUpdateDelegate(UpdateTextBox); /實(shí)傷必匕委托對象spSe nd.Ope n();/SerialPort對象在程序結(jié)束前必須關(guān)閉,在此說明spReceive.DataReceived += Ports.SerialDataReceivedEve ntHa ndler(spReceive_DataReceive d);spReceive.Re

13、ceivedBytesThreshold = 1; spReceive.Ope n();)public void btnSen d_Click(object sen der,Eve ntArgs e) (spSe nd.WriteL in e(txtSe nd.Text); )public void spReceive_DataReceived(object sen der,Ports.SerialDataReceivedEve ntArgs e) (byte readBuffer = new bytespReceive.ReadBufferSize;spReceive.Read(readBu

14、ffer, 0, readBuffer.Le ngth);this .In voke(i nterfaceUpdateHa ndle, new stri ng En cod ing.Uni code.GetStri ng(readBuffer) ); private void UpdateTextBox(string text)txtReceive.Text = text;)點(diǎn)評:這個例子包括了這個控件幾乎所有的操作,非常有參考價值.serialPort是在.netframework2.0中才有的東西,感覺這個東西和MSCOMM很相似.這里給出的例子是基于和CSHAPE的,相應(yīng)的可以在Csha

15、pe和C+中使用,基本上都是一樣的.Imports SystemImports System JO. PortsImports System. ThreadingPublic Class PortChatShared ,continue As BooleanShared _serialPort As SerialPortPublic Shared Sub Main ()Dim name As StringDim message As StringDim sComparer As StringComparer =StringComparer. OrdinallgnoreCaseDim readT

16、hread As Thread = NewThread (AddressOfRead'Create a newSerialPort object with default settings .serialPort = NewSerialPort ()'Allow the user to set the appropriateproperties .serialPort. PortName =SetPortName( .serialPort. PortName)serialPort. BaudRate =SetPortBaudRate (serialPort. BaudRate)

17、serialPort . Parity =SetPortParity (serialPort . Parity )serialPort. DataBits =SetPortDataBits (serialPort . DataBits )serialPort. StopBits =SetPortStopBits (serialPort . StopB讓s )serialPort. Handshake =SetPortHandshake(serialPort . Handshak©'Set the read / write timeoutsreadThread. Start (

18、)Console. WHte (“Name:”)n ame = Con sole . ReadL in e()Console. WriteLine ("Type QUIT to exit11)While (continue )message = Con sole . ReadL in e()Dim newPortName As StringConsole.WriteLine ("Available Ports:")Dim s As StringFor Each s In SerialPort. GetPortNames() Console.WriteLine (&

19、quot; 0", s) Next sConsole. Write ("COM port(0):f, defaultPortName ) n ewPortName = Con sole . ReadL in e()If newPortName = 'H, Thenn ewPortName = defaultPortNameEnd IfRetur n n ewPortNameEnd FunctionPublic Shared Function SetPortBaudRate (ByVai defaultPortBaudRate As Integer) As Integ

20、erDim newBaudRate As StringConsole. Write (''Baud Rate(0):H defaultPortBaudRate)n ewBaudRate = Con sole . ReadL in e()If newBaudRate = ,n Thenn ewBaudRate = defaultPortBaudRate . ToString0fEndlfReturn Integer. Parse(newBaudRateEnd FunctionPublic Shared Function SetPortParity (ByVai defaultPo

21、rtParity As Parity ) As ParityDim newParity As StringCon sole. WriteL ine ("Available Parity options:*)Dim s As StringFor Eachs In Enum GetName$GetType(Parity )Console. WriteLine (" 0”, s)Next sCon sole. Write ("P arity(O):n defaultPortParity .ToString ()n ewparity = Con sole . ReadL

22、in e()If newparity = Then n ewparity =.ToString ()defaultPortParity End IfReturn CTyp& Enurji Parse( GetType( Parity ), newParity), Parity)End FunctionPublic Shared Function SetPortDataBits (ByVai defaultPortDataBits As Integer) As IntegerDim newDataBits As StringConsole. Write ("Data Bits(

23、0):n,defaultPortDataBits)CTyp& Enurji Parse( GetType(StopBits ), newStopBits ), StopBits ) EndFunctionPublic Shared Function SetPortHandshake (ByVai defaultPortHandshake As Handshake) As HandshakeDim newHandshake As StringCon sole. WriteL ine ("Available Ha ndshake options/*)Dim s As String

24、For Each s InEnurji GetName$GetType(Handshak©)Console. WriteLine (" 0”, s)Next sCon sole. Write ("Stop Bits(0):H,defaultPortHandshake . ToString ()n ewHa ndshake = Con sole . ReadL in e()If newHandshake = "" Thenn ewHa ndshake =defaultPortHandshake . ToString ()End IfRetur n

25、CTyp& Enurji Parse(GetType( Handshak©, newHandshak©, Handshake)End FunctionEnd Classusing System;using System. IO. Ports ;using System. Threading ;public class PortChatstatic bool .continue ;static SerialPort serialPort;public static void Main ()stri ng n ame;stri ng messageStri ngComp

26、arer stri ngComparer =Strin gComparer . Ordin allg no reCase ;Thread readThread = n ew Thread( Read;/ Create a new SerialPort object with default sett in gs._serialPort = n ewSerialPort ();/ Allow the user to set the appropriateproperties._serialPort. PortName = SetPortName(_serialPort.PortName);_se

27、rialPort. BaudRate = SetPortBaudRate (_serialPort.BaudRate);_serialPort. Parity =SetPortParity (_serialPort. Parity );_serialPort. DataBits = SetPortDataBits (_serialPort.DataBits );_serialPort. StopBits = SetPortStopBits (_serialPort.StopBits);serialPort. Handshake =SetPortHandshake(_serialPort. Ha

28、ndshak©/ Set the read/write timeouts_serialPort. ReadTimeout = 500;_serialPort. WriteTimeout = 500;_serialPort. Oper();.continue = true ;readThread. Start ();Con sole. Write ("Name:");n ame = Con sole. ReadL in e();Console. WriteLine ("Type QUIT to exit11);while (continue )messag

29、e = Con sole. ReadL in e();if (stri ngComparer. Equals ("quit", message)_continue = false ;)else_serialPort. WriteLine (String . Format(nv0>: (D",name, message );) )readThread.Join ();_serialPort .Close ();public static void Read()while ( _continue )trystri ng message =Console. Wri

30、teLine ("Available Ports:");foreach (string s in SerialPort. GetPortNames()Con sole. WriteLi ne (" 0“,s);Console. Write (“COM port(0):H, defaultPortName );portName = Con sole. ReadL in e();if (portName ="")portName = defaultPortName ; return portName;public static int SetPor

31、tBaudRate (intdefaultPortBaudRate ) (string baudRate;Con sole. Write ("Baud Rate(0):H defaultPortBaudRate );baud Rate = Con sole. ReadL in e();if (baudRate ="")baud Rate = defaultPortBaudRate . ToString ();return int. Parse( baudRate);public static Parity SetPortParity (Parity default

32、PortParity )stri ng parity ;Con sole. WriteL ine ("Available Parity options/*);foreach (string s in EnumGetNamestypeof (Parity)Con sole. WriteLi ne (H 0H, s);Con sole. Write (T arity(O):n , defaultPortParity ToString ();parity = Con sole. ReadL in e();if (parity ="") (parity = default

33、PortParity . ToString (); return (Parity ) EnumParse(typeof (Parity ), parity);public static int SetPortDataBits (int defaultPortDataBits )(stri ng dataBits ;Con sole. Write ("Data Bits(0):n defaultPortDataBits );dataBits = Con sole. ReadL in e();if (dataBits ="") (dataBits =defaultPo

34、rtDataBits .ToString ();return int. Parse( dataBits );public static StopBits SetPortStopBits (StopBits defaultPortStopBitsstri ng StopBits ;Con sole. WriteL ine ("Available Stop Bits options:*');foreach (string s inEnumGetNamestypeof (StopBits )Con sole. WriteLi ne (" 0”, s);Con sole.

35、Write ("Stop Bits(0):" defaultPortStopBits .ToString ();StopBits = Con sole. ReadL in e(); ll! if (stopBits)StopBits defaultPortStopBits .ToString ();return (StopBits ) EnumParse(typeof (StopBits ),stopBits);public static Handshake SetPortHandshake (HandshakedefaultPortHandshake )string ha

36、ndshake ;Con sole. WriteL ine ("Available Han dshake options:"); foreach (string s inEnumGetNamestypeof (Handshak©)(Con sole. WriteLi ne (', 0'*, s);)Con sole. Write (“Stop Bits(O):H defaultPortHandshake . ToString ();han dshake = Con sole. ReadL in e();if (handshake ="&q

37、uot;)(handshake = defaultPortHa ndshake .ToString (); return(Handshak© EnumParse(typeof (Handshak©, handshake);SerialPort類的源代碼已經(jīng)放在下面,SerialPort類是由Remon Spekreijse提供的免費(fèi)串口類。CSerialPort支持線連接的串口編程,而且是基于多線程的,工作流程:1 .設(shè)置串口參數(shù)。 函數(shù)原型:BOOL CSerialPort:lnitPort(CWnd* pPortOwner, / the owner (CWnd) of

38、the port (receives message)UINT portnr, / portnumber (1.4)UINT baud, / baudrate char parity, / parityUINT databits, / databitsUINT stopbits, / stopbitsDWORD dwCommEvents, / EV RXCHAR, EV CTS etcUINT writebuffersize) / size to the writebuffer2 .串口監(jiān)測線程。BOOL CSerialPort:StartMonitoring()BOOL CSerialPor

39、t:RestartMonitoring()BOOL CSerialPort:StopMonitoring()void CSerialPort:WriteChar(CSerialPort* port)void CSerialPort:ReceiveChar(CSerialPort* port, COMSTAT comstat) void CSerialPort:WriteToPort(char* string)3 .監(jiān)測線程接收事件信息,再進(jìn)行消息處理即可。SerialPort類的應(yīng)用基于對話框的串口程序開發(fā):1 ,將SerialPort類添加進(jìn)工程;2 .進(jìn)行消息的映射;(注意:在Serial

40、Port類的頭文件中的:#define WM_COMM_RXCHAR WM_USER+7需要手動進(jìn)行映射)在工程的主對話框頭文件中,格式如下:afx_msg LONG OnComm(WPARAM ch,LPARAM port);在工程的主對話框的CPP文件中,格式如下:BEGIN_MESSAGE_MAP(CMy20040889SerialPortTestDlg, CDialog) AFX_MSG_MAP(CMy20040889SerialPortTestDlg)ON_MESSAGE(WM_COMM_RXCHAR,OnComm) AFX_MSG_MAPEND_MESSAGE_MAP()然后在CP

41、P中添加消息處理函數(shù),本例中為 OnComm。例如:LONG CTestDlg:OnComm(WPARAM ch, LPARAM port)(m_strEditReceiveMsg += ch;UpdateData(FALSE);return 0;) m_strEditReceiveMsg為EDIT控件(接收框)的變量。下面的m strEditSendMsg同樣處理。3實(shí)現(xiàn)串口的初始化,打開/關(guān)閉串口按鈕的響應(yīng)函數(shù),最后是發(fā)送信息按鈕的函數(shù)實(shí)現(xiàn)void CTestDlg:OnButtonOpen()int nPort=m_ctrlComboComPort.GetCurSel()+1;if(m_

42、SerialPort.lnitPort(this, nPort, 9600;N'J8,1,EV_RXFLAG | EV_RXCHAR,512) m_SerialPort.StartMonitoring();m_bSerialPortOpened=TRUE;)elseAfxMessageBox("沒有發(fā)現(xiàn)此串口或被占用");m_bSerialPortOpened=FALSE;GetDlgltem(IDC_BUTTON_OPEN)->EnableWindow(!m_bSerialPortOpened);GetDlgltem(IDC_BUTTON_CLOSE)-&g

43、t;EnableWindow(m_bSerialPortOpened);)void CTestDlg:OnButtonClose()(m_SerialPort.ClosePort();m_bSerialPortOpened=FALSE;GetDlgltem(IDC_BUTTON_OPEN)->EnableWindow(!m_bSerialPortOpened);GetDlgltem(IDC_BUTTON_CLOSE)->EnableWindow(m_bSerialPortOpened);)void CTestDlg:OnButtonSend()if(!m bSerialPortOp

44、ened) return; UpdateData(TRUE); / 讀入編輯框中的數(shù)據(jù)m_SerialPort.WriteToPort(LPCTSTR)m_strEditSendMsg);/ 發(fā)送數(shù)據(jù))傳感器(c#2.0)serialPort 串口通訊 2007 年 10 月 12 日 星期五 15:44 using System;using System.Collectio ns.Ge neric;using System.Comp onen tModel; using System.Data;using System.Data.SqlClie nt;using System.Drawi n

45、g;using System.Text;using System.Wi ndows.Forms;using System.Configuration;using Syste m.lO;using Syste m.lO .Ports;n amespace Win dowsApplicatio n2public partial class Forml : Form(public Forml ()(In itializeComp onen t();int iCo unt; int nu mbers; byte rlen th; bool bRLe nth; int bRStart; bool bRP

46、aram; byte Rchk; int LParam; byte RParam; bool brcmd; byte RCmd; bool bRchk; bool bfini sh;private void Form 1 _Load(object sender. EventArgs e) / Forml Forml = new Form1(); try (if (this.serialPortl .IsOpe n) else(串口 COM1 設(shè)置通信口參數(shù)8;/數(shù)據(jù)位System.IO.Ports.Parity.No ne; /System.IO.Ports.StopBits.O ne; 10

47、24;1024;立rzg+巨1;serialPortl .Close();serialPortl ,PortName= "COM1" / 選擇serialPortl .BaudRate= 9600;/serialPortl .DataBits =serialPortl .Parity =校驗(yàn)位無校驗(yàn)serialPortl .StopBits =停止位1位serialPortl .ReadBufferSize =接收緩沖區(qū)大小serialPortl .WriteBufferSize =發(fā)送緩沖區(qū)大小serialPortl .Ope n();serialPortl .ReadE

48、xisti ng();設(shè)置In put從接收緩沖讀取全serialPortl .ReceivedBytesThreshold =設(shè)置引發(fā)On Com事件的字節(jié)長度 serialPortl .Discardl nBuffer();清除接收緩沖區(qū)serialPortl .DiscardOutBuffer();清除發(fā)送緩沖區(qū)stri ng conn str =System.C on figurati on .C on figurati onMan ager.AppSetti ngsnmyCo nn ectio nSt rin g"SqlC onnection conn = newSqlCo

49、 nn ectio n(co nn str);conn. Ope n(); string sql = "selectn ame as時間,price,card from testOI',;SqlDataAdapter da = new SqlDataAdapter(sql, conn);DataSet ds = new DataSet(); da.Fill(ds, "baomi nH);ultraChartl .DataSource =ds.TablesO.DefaultView;dataGridViewl .DataSource =ds.TablesO. Defa

50、ultView;ultraChartl .Axis.Y Log Base = 1000;ultraChartl .Axis.Y.Ra ngeMax = 30000;ultraChartl .Axis.Y.Ra ngeMin = 0; Applicatio n.E nableVisualStyles(); Applicatio n.DoEve nts();)catch (Exceptio n ex) MessageBox.Show("ddM,ex.Message,Mess ageBoxButt on s.OK,MessageBoxlc on .Error);/ ultraChartl.

51、)/<summary>III取前后存儲器兩個值對比,應(yīng)付電腦異常退出III </summary>III <param name=',senderH>XOR 異域校驗(yàn) v/param>III <param n ame=,'e',x/param>private void serialPort1_DataReceived(object sen der, SerialDataReceivedEve ntArgs e)(try(/Byte dataread = new Byte8;/serialPortl .Read(data

52、read, 0,dataread _L en gth);Hint productline=dataread0; / 接口/iCoun t=dataread5;stri ng conn str =System.C on figurati on .C on figurati onMan ager.AppSetti ngsnmyCo nn ectio nSt rin g"SqlC onnection conn = newSqlCo nn ecti on(conn str);conn. Ope n();/if (datareadO = OxAA)/ IIIIMessageBox.Show(p

53、roductli ne.ToStri ng(), “ddd”,MessageBoxButt on s.OK, MessageBoxIc on .Error);/nu mbers= 0;/nu mbers=Con vert.Tol nt32(dataread4) * 256 A 1 + Con vert.Tol nt32(dataread 5);/nu mbers=Con vert.Tol nt32(dataread4) * Con vert.Tol nt32(System.Math.Pow(256,1) + Co nvert.Tol nt32(dataread 5);/SqlComma nd

54、cmd = newSqlComma nd(,'SP_SCJN_AUTONUMBERn, conn);/cmd.Comma ndType =Comma ndType.StoredProcedure;/cmd.Parameters.Add(nqua ntity1', SqlDbType.l nt);/cmd.Parameters"qua ntityn.Value = nu mbers;/cmd.Parameters.Add("portsH, SqlDbType.l nt);/cmd.Parameters"ports".Value = data

55、read3;/cmd.ExecuteN on Query();/)byte DataRead;int bytData ;int byt num;/byt num = serialPortl.ReadByte;/TODO: Notlmpleme nted stateme nt:ICSharpCode.SharpRefactory.Parser.AST.VB.O nErrorStateme ntif(serialPortl .ReceivedBytesThreshold = serialPortl .ReceivedBytesThreshold)(byt num = serialPortl .By

56、tesToRead;DataRead = new bytebyt nu m;/TODO: Notlmpleme nted statement: ICSharpCode.SharpRefactory.Parser.AST.VB. ReDimStateme ntfor (int k = 0; k <= (byt num -1);k+) bytData= serialPortl .ReadByte();DataReadk =(byte)byt Data;bfinish =RFJ(DataReadk);if (bfi nish)(/System.C onvert.Tolnt32(RCmd)為端口號iCou nt = 0;for (int j =0; j <= 1 ; j+)(iCount += System.Co nvert.Tol nt32(RParamj) * Con vert.Tol nt32(Math.Pow(256, j);SqlComma ndcmd = new SqlComma nd("

溫馨提示

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

評論

0/150

提交評論