Imports System
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel
Public Class Form1
Dim myPort As Array
Private Sub GetSerialPortNames()
For Each sport As String In My.Computer.Ports.SerialPortNames
portComboBox.Items.Add(sport)
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim BaudRates() As String = {"300", "1200", "2400", "4800", "9600", "14400", "19200", "28800", "38400", "57600", "115200"}
baudComboBox.Items.AddRange(BaudRates)
baudComboBox.SelectedIndex = 4
Try
GetSerialPortNames()
baudComboBox.SelectedIndex = 0
Catch
MsgBox("No ports connected.")
End Try
Timer1.Stop()
End Sub
Private Sub connectBotton_Click(sender As Object, e As EventArgs) Handles connectBotton.Click
SerialPort1.PortName = portComboBox.Text
SerialPort1.BaudRate = baudComboBox.Text
SerialPort1.DataBits = 8
SerialPort1.StopBits = IO.Ports.StopBits.One
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.Open()
Timer1.Interval = 500
Timer1.Start()
portComboBox.Enabled = False
baudComboBox.Enabled = False
connectBotton.Enabled = False
disconnectBotton.Enabled = True
End Sub
Private Sub closeBotton_Click(sender As Object, e As EventArgs) Handles disconnectBotton.Click
SerialPort1.Close()
Timer1.Stop()
portComboBox.Enabled = True
baudComboBox.Enabled = True
connectBotton.Enabled = True
disconnectBotton.Enabled = False
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
SerialPort1.Close()
Timer1.Stop()
portComboBox.Enabled = True
baudComboBox.Enabled = True
connectBotton.Enabled = True
disconnectBotton.Enabled = False
End
End Sub
Delegate Sub myMethodDelegate(ByVal [text] As String)
Dim myDelegate As New myMethodDelegate(AddressOf ShowString)
Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim str As String = SerialPort1.ReadExisting()
Invoke(myDelegate, str)
End Sub
Sub ShowString(ByVal myString As String)
outputTextBox.AppendText(myString)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
outputTextBox.Clear()
End Sub
End Class
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim com1 As IO.Ports.SerialPort = Nothing
Try
com1 = My.Computer.Ports.OpenSerialPort("COM1")
com1.ReadTimeout = 10000
Do
Dim Incoming As String = com1.ReadLine()
If Incoming Is Nothing Then
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
Loop
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If com1 IsNot Nothing Then com1.Close()
End Try
Return returnStr
End Function