VB.NET 串口访问之四(绝密级)

页面导航:首页 > 软件编程 > vb.net > VB.NET 串口访问之四(绝密级)

VB.NET 串口访问之四(绝密级)

来源: 作者: 时间:2016-01-18 16:54 【

Imports System.IOImports System.IO.PortsImports System.Runtime.Remoting.Messaging #39;这个不忘记Imports System.TextDelegate Function CommOp(ByVal pval As String, ByVal pDelay As Int...

Imports System.IO 

Imports System.IO.Ports 

Imports System.Runtime.Remoting.Messaging   '这个不忘记 

Imports System.Text 

 

Delegate Function CommOp(ByVal pval As String, ByVal pDelay As Integer) As String 

 

 

 

Module Module1 

 

    Public WithEvents Rs232 As SerialPort 

    Sub Main() 

 

        Rs232 = New SerialPort("COM1", 9600, Parity.None, 8, StopBits.One) 

        If Rs232.IsOpen Then Exit Sub 

        Rs232.Open() 

 

        Console.WriteLine("*******执行串口操作*********") 

        Dim c As CommOp = New CommOp(AddressOf CommOpWrite) 

        c.BeginInvoke("ssssssss", 50, Nothing, Nothing) 

 

 

        ' Dim itfAR As IAsyncResult = c.BeginInvoke("ssssssss", 50, New AsyncCallback(AddressOf CommOpComplete), "操作完成") 

 

        '继续其他工作 

 

 

        Console.ReadLine() 

    End Sub 

 

    ' 

    Sub CommOpComplete(ByVal itfAR As IAsyncResult) 

        Console.WriteLine("已经完成数据处理") 

 

        Dim ar As AsyncResult = CType(itfAR, AsyncResult) 

        Dim c As CommOp = CType(ar.AsyncDelegate, CommOp) 

 

        Console.WriteLine("输出的结果", c.EndInvoke(itfAR).ToString) 

 

        '接受返回的信息 

        Dim Msg As String = CType(itfAR.AsyncState, String) 

        Console.WriteLine(Msg) 

 

 

    End Sub 

 

    Function CommOpWrite(ByVal pVal As String, ByVal pDelay As Integer) As String 

        Rs232.Write(pVal) 

 

        Threading.Thread.Sleep(pDelay) 

 

        Dim buf() As Byte 

        Dim Builder As StringBuilder = New StringBuilder '避免在事件处理方法中反复的创建,所以定义到外面  

 

        '[email protected],返回>0F00 +vbcrlf 

        Dim TT As Integer 

        Dim bTimeOver As Boolean = False 

 

        TT = Environment.TickCount 

        bTimeOver = False 

        Do 

            If Rs232.BytesToRead >= 5 Then Exit Do 

            If Environment.TickCount - TT > 1000 Then bTimeOver = True 

        Loop Until bTimeOver 

 

        If bTimeOver Then 

            Return String.Empty 

        Else 

            Dim n As Integer = Rs232.BytesToRead 

            ReDim buf(n - 1) 

            Rs232.Read(buf, 0, n) 

            For Each b As Byte In buf 

                Builder.Append(b.ToString("X2") + " ") 

            Next 

 

            Console.WriteLine(Builder.ToString) 

            Return Builder.ToString 

 

        End If 

    End Function 

 

 

End Module   摘自:wl58796351的专栏

 

Tags:

文章评论

最 近 更 新
热 点 排 行
Js与CSS工具
代码转换工具

<