'加载本机所有的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