加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

vb.net串口通信(SerialPort控件)

发布时间:2020-12-16 23:15:08 所属栏目:大数据 来源:网络整理
导读:'加载本机所有的com Sub GetSerialPortNames() For Each sp As String In My.Computer.Ports.SerialPortNames ComboBox1.Items.Add(sp) Next If ComboBox1.Items.Count 0 Then ComboBox1.SelectedIndex = 0 End If End Sub '打开串口 If SerialPort1.IsOpen

'加载本机所有的com

Sub GetSerialPortNames()
For Each sp As String In My.Computer.Ports.SerialPortNames
ComboBox1.Items.Add(sp)
Next
If ComboBox1.Items.Count > 0 Then
ComboBox1.SelectedIndex = 0
End If
End Sub

'打开串口

If SerialPort1.IsOpen Then
SerialPort1.Close()
End If

Try
With SerialPort1
.PortName = ComboBox1.Text
.BaudRate =9600

.Parity = IO.Ports.Parity.None '奇偶校验
.DataBits = 8 '数据位
.StopBits = IO.Ports.StopBits.One '停止位
End With
'打开
SerialPort1.Open()

Label1.Text = "Connected"
Button1.Enabled = False
Button2.Enabled = True
Catch ex As Exception
MsgBox(ex.ToString)
End Try

'关闭串口

SerialPort1.close()

'发送数据

一般的数据

dim data as string=textbox1.text

SerialPort1.write(data)

十六进制字符串

发送十六进制字符串时,我们用数组保存要发送的信息

比如发送数据为:FF 01 00 00 01 00 00 FE

Try
Dim data(8) As Byte
data(0) = &HFF
data(1) = &H1
data(2) = &H0
data(3) = &H0
data(4) = &H1
data(5) = &H0
data(6) = &H0
data(7) = &HFE
SerialPort1.DiscardOutBuffer()
SerialPort1.Write(data,8)
Catch ex As Exception
MsgBox(ex.ToString)
End Try

接收数据

SerialPort有个DataReceived事件,我们可以在里面写接受数据代码

接受字符串:SerialPort.ReadExisting

接受流数据:

dim byteToRead as int16=SerialPort.bytestoread(读取缓冲区的字节长度)

dim ch(byteToRead) as byte

dim bytesRead as int16=0

bytesRead=SerialPort.read(ch,bytetoread)

for i as int16=0 to bytesRead-1

indata=indata & DecToHex(ch(i))

next

indata 就是读取到的数据

自定义函数:DecToHex (返回十六进制字符)

Public Function DecToHex(ByVal DecNumber As Byte) As String '转换成十六进制字符串 If DecNumber <= 15 Then DecToHex = " 0" & Hex(DecNumber) Else : DecToHex = " " & Hex(DecNumber) End If End Function

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读