前端之家收集整理的这篇文章主要介绍了
VB.NET 串口访问之四(绝密级),
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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",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("输出的结果{0}",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 '避免在事件处理方法中反复的创建,所以定义到外面
'输入模块的命令是@01,返回>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,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