Vb.net SerialPort串口通信例程
使用Vb.net进行串口操作,利用官方提供接口SerialPort。
定义串口对象
Imports System.IO.Ports
Public WithEvents Port As New SerialPort '串口对象
获取电脑串口
Sub GetSerialPortNames() '获取电脑COM口列表
Com_scan.Items.Clear()
For Each sp As String In My.Computer.Ports.SerialPortNames
Com_scan.Items.Add(sp)
Next
If Com_scan.Items.Count > 0 Then
Com_scan.Sorted = True
Com_scan.SelectedIndex = 0
End If
End Sub
串口参数设定
Port.PortName = Com_scan.Text ’串口名称
Port.BaudRate=Val(ComboBoxBaudRate.Text) '串口波特率
Port.Parity = ComboParity.SelectedIndex '串口奇偶校验
Port.DataBits = Val(ComboDataBits.Text) '串口数据位长度
Port.StopBits = Val(ComboBoxStopBits.Text) '串口停止位
If Not Port.IsOpen Then
Port.Open()
Label1.Text = "串口已打开"
Label1.ForeColor = Color.Green
End If
串口发送数据
'文本发送
Port.Write(TextBoxSend.Text.Replace(" ", "")) 'Text.Replace删除其中空格再发送
'十六进制发送
outDataBuf = outDataBuf.Replace(" ", "") '清除空格与回车
outDataBuf = outDataBuf.Replace(vbNewLine, "")
If outDataBuf.Length Mod 2 <> 0 Then
MsgBox("请输入正确的十六进制数,用空格和回车隔开。")
Exit Sub
End If
Dim outBytes(outDataBuf.Length / 2 - 1) As Byte
For I As Integer = 1 To outDataBuf.Length - 1 Step 2
outBytes((I - 1) / 2) = Val("&H" + Mid(outDataBuf, I, 2))
Next
Port.Write(outBytes, 0, outDataBuf.Length / 2)
串口数据回调函数
'文本显示
Private Sub Port_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles Port.DataReceived
RichTextBox1.Invoke(RecieveRefresh, Port.ReadExisting) '委托
End Sub
'十六进制显示
Dim inDataLen As Integer = Port.BytesToRead()
If inDataLen > 0 Then
Dim inBytes(inDataLen - 1) As Byte, bytes As Byte
Dim strHex As String = ""
Port.Read(inBytes, 0, inDataLen)
For Each bytes In inBytes
strHex = strHex + [String].Format("{0:X2} ", bytes)
Next
receivebox.Invoke(RecieveRefresh, strHex)
End If
委托定义、数据显示
Delegate Sub RecieveRefreshMethodDelegate(ByVal [text] As String) '声明委托
Dim RecieveRefresh As New RecieveRefreshMethodDelegate(AddressOf RecieveRefreshMethod) '定义一个委托实例
Sub RecieveRefreshMethod(ByVal str As String) '数据处理
RichTextBox1.Text += str
End Sub