' Load native all COM
Sub Getserialportnames ()
For the 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
' Open the serial port
If Serialport1.isopen Then
Serialport1.close ()
End If
Try
with SerialPort1
. PortName = Combobox1.text
. BaudRate = 9600
. Parity = IO. Ports.Parity.None ' Parity
. DataBits = 8 ' data bit
. StopBits = IO. Ports.StopBits.One ' Stop bit
end with
' Open
Serialport1.open ()
Label1.Text = "Connected"
button1.enabled = False
button2.enabled = True
Catch ex as Exception
MsgBox (ex. ToString)
End Try
' Close the serial port
Serialport1.close ()
' Send data
General data
Dim data As String=textbox1.text
Serialport1.write (data)
hexadecimal string
When sending a hexadecimal string, we use an array to save the information to be sent
For example, send data: FF-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, 0, 8)
Catch ex as Exception
MsgBox (ex. ToString)
End Try
Receive data
SerialPort has a datareceived event where we can write the accepted data code.
Accept string: serialport.readexisting
Accept Stream Data:
Dim bytetoread As Int16=serialport.bytestoread (byte length of read buffer)
Dim ch (bytetoread) as Byte
Dim bytesread As Int16=0
Bytesread=serialport.read (Ch,0,bytetoread)
For I as int16=0 to BytesRead-1
Indata=indata & Dectohex (CH (i))
Next
Indata is the data that is read
Custom Function: Dectohex (return hexadecimal character)
Public Function Dectohex (ByVal decnumber as Byte) As String ' converts to a hexadecimal string
If Decnumber <= Then
Dectohex = "0" & Hex (Decnumber)
Else:dectohex = "" & Hex (Decnumber)
End If
End Function