×

VB.net2005 SerialPort组件串口编程

Kalet Kalet 发表于2009-03-20 12:00:13 浏览307 评论0

抢沙发发表评论

1、数据发送


VB.net2005 SerialPort组件串口编程

 此部分比较简单,调用SerialPort的write方法即可


  '定义mStr的十六进制字符串


  dim mStr as string="245159535A002700000001650103457812104E140806458012104E140806457812104E0A0806E9"


Dim mSndData() As Byte = {0}
mSize = mStr.Length / 2 - 1
ReDim mSndData(mSize)
For j = 0 To mSize
mTemp = mStr.Substring(j * 2, 2)
mSndData(j) = xa2di(mTemp)  '十六进制字符串转换为十进制数字
Next
 Me.SerialPort1.Write(mSndData, 0, mSndData.Length)


2、数据接收


Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim mRecvData() As Byte
Dim mSize As Integer = Me.SerialPort1.BytesToRead
ReDim mRecvData(mSize - 1)
Dim mHexByte As String = ""
Dim mTempStr As String = ""
Dim i As Integer
If mSize = 0 And mRecvStr.Length > 0 Then
mTempStr = mRecvStr.Replace(" ", "")


      '收到的字符长度是否与定义长度相等
If Me.xa2di(mTempStr.Substring(10, 4)) = mTempStr.Length / 2 Then         


         '此处开始数据处理mRecvStr内容


   mRecvStr = ""
End If
Exit Sub
End If
Me.SerialPort1.Read(mRecvData, 0, mSize)
For i = 0 To mSize - 1
mHexByte = IIf(mRecvData(i) > 15, Hex(mRecvData(i)), "0" & Hex(mRecvData(i)))

VB.net2005 SerialPort组件串口编程

      '每个数据包以十六进制数“24”开头,每包10位到14位定义包长度
If mHexByte = "24" Then
If mRecvStr = "" Then
mRecvStr = mHexByte
Else
mTempStr = mRecvStr.Replace(" ", "")
If mTempStr.Length > 14 Then


            '收到的字符长度是否与定义长度相等
If Me.xa2di(mTempStr.Substring(10, 4)) = mTempStr.Length / 2 Then


               '此处开始数据处理mRecvStr内容


  mRecvStr = mHexByte
Else
mRecvStr &= " " & mHexByte
End If
Else
mRecvStr &= " " & mHexByte
End If
End If
Else
mRecvStr &= " " & mHexByte
mTempStr = mRecvStr.Replace(" ", "")
If mTempStr.Length > 14 Then
          '收到的字符长度是否与定义长度相等
If Me.xa2di(mTempStr.Substring(10, 4)) = mTempStr.Length / 2 Then


            '此处开始数据处理mRecvStr内容


mRecvStr = ""
End If
End If
End If
Next
End SubVB.net2005 SerialPort组件串口编程



群贤毕至

访客