Paso 1: Visual Studio
1. agregar lo siguiente al formulario de Windows en la vista Diseño:
- Temporizador y lo llaman TimerConnect.
- ListBox y lo llaman lstConsole.
- Botón y llamarlo btnConnect.
2. Agregar referencia IO puertos en la parte superior del código:
Imports System.IO.Ports
3. establecer una variable global del principio de la clase pública:
Dim ArduinoConnected As Boolean
4. Agregar a tu submarino de carga de formulario:
TimerConnect.Enabled = FalseArduinoConnected = Falseautoconnect()
3. añadir estos subs a la secuencia de comandos:
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