Kod:
Imports System
Imports System.IO.Ports
Public Class Form1
Dim comPORT As String
Dim receivedData As String = ""
Dim connected As Boolean = False
Dim count = 0
Dim Data As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Enabled = False
populateCOMport()
End Sub
Private Sub refreshCOM_BTN_Click(sender As Object, e As EventArgs) Handles refreshCOM_CB_BTN.Click
SerialPort1.Close()
populateCOMport()
End Sub
Private Sub populateCOMport()
comPORT = ""
comPort_ComboBox.Items.Clear()
For Each sp As String In My.Computer.Ports.SerialPortNames
comPort_ComboBox.Items.Add(sp)
Next
End Sub
Private Sub comPort_ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles comPort_ComboBox.SelectedIndexChanged
If (comPort_ComboBox.SelectedItem <> "") Then
comPORT = comPort_ComboBox.SelectedItem
End If
End Sub
Private Sub connect_BTN_Click(sender As Object, e As EventArgs) Handles connect_BTN.Click
comPORT = comPort_ComboBox.SelectedItem
If (connect_BTN.Text = "Connect") Then
If (comPORT <> "") Then
SerialPort1.Close()
SerialPort1.PortName = comPORT
SerialPort1.BaudRate = 9600
SerialPort1.DataBits = 8
SerialPort1.Parity = Parity.None
SerialPort1.StopBits = StopBits.One
SerialPort1.Handshake = Handshake.None
SerialPort1.Encoding = System.Text.Encoding.Default
SerialPort1.ReadTimeout = 10000
SerialPort1.Open()
'Jak arduino sie odezwie
count = 0
SerialPort1.WriteLine("<HELLO>")
connect_BTN.Text = "Connecting..."
connecting_Timer.Enabled = True
Else
MsgBox("Select a COM port first")
End If
Else
Timer1.Enabled = False
Timer_LBL.Text = "Timer: OFF"
SerialPort1.Close()
connected = False
connect_BTN.Text = "Connect"
populateCOMport()
End If
End Sub
Private Sub connecting_Timer_Tick(sender As Object, e As EventArgs) Handles connecting_Timer.Tick
connecting_Timer.Enabled = False
count = count + 1
If (count <= 8) Then
receivedData = receivedData & ReceiveSerialData()
If (Microsoft.VisualBasic.Left(receivedData, 5) = "HELLO") Then
'if we get an HELLO from the Arduino then we are connected
connected = True
connect_BTN.Text = "Dis-connect"
Timer1.Enabled = True
Timer_LBL.Text = "Timer: ON"
receivedData = ReceiveSerialData()
receivedData = ""
SerialPort1.WriteLine("<START>")
Else
'start the timer again and keep waiting for a signal from the Arduino
connecting_Timer.Enabled = True
End If
Else
'time out (8 * 250 = 2 seconds)
RichTextBox1.Text &= vbCrLf & "ERROR" & vbCrLf & "Can not connect" & vbCrLf
connect_BTN.Text = "Connect"
populateCOMport()
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
receivedData = ReceiveSerialData()
RichTextBox1.Text &= receivedData 'w tym miejscu prawidłowo odbiera i wyświetla dane
End Sub