Vb.net SerialPort串口通信例程

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MJD1937

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值