Stap 1: Visual Studio
1. het volgende toevoegen aan uw Windows-formulier in de ontwerpweergave:
- Timer en noemen het TimerConnect.
- ListBox en noemen het lstConsole.
- Knop en noemen het btnConnect.
2. Voeg referentie IO poorten boven van code:
Imports System.IO.Ports
3. Stel een globale variabele aan het begin van de Public Class:
Dim ArduinoConnected As Boolean
4. deze toevoegen aan uw sub Form Load:
TimerConnect.Enabled = FalseArduinoConnected = Falseautoconnect()
3. Voeg deze subs aan het script:
Private Sub BtnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click If ArduinoConnected Then SerialPort.Close() btnConnect.Text = "Connect" Else autoconnect() End If End Sub
Private Sub autoconnect() For Each sp As String In My.Computer.Ports.SerialPortNames Try SerialPort.PortName = sp SerialPort.BaudRate = 9600 SerialPort.DataBits = 8 SerialPort.Parity = Parity.None SerialPort.StopBits = StopBits.One SerialPort.Handshake = Handshake.None SerialPort.Encoding = System.Text.Encoding.Default SerialPort.Open() SerialPort.Write("3/") TimerConnect.Interval = 500 TimerConnect.Start() While TimerConnect.Enabled And ArduinoConnected = False Application.DoEvents() End While If ArduinoConnected Then btnConnect.Text = "Disconnect" Exit For End If SerialPort.Close() Catch ex As Exception MsgBox(ex.Message) End Try Next If ArduinoConnected = False Then MsgBox("Arduino failed to connect. Please check that it is plugged in.") End IfEnd Sub
Public Sub TimerConnect_Tick(sender As Object, e As EventArgs) Handles TimerConnect.Tick TimerConnect.Stop()End Sub
Public Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived Dim str As String = SerialPort.ReadExisting() If str.Contains("Arduino") Then ArduinoConnected = True lstConsole.Items.Add("Arduino Connected") End IfEnd Sub