Вы находитесь на странице: 1из 125

Lectura de entradas digitales con

Arduino y Visual Studio 2015

ngel Acaymo M. G.
Electrnica PIC
http://electronica-pic.blogspot.com.es
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

ndice

Qu puerto uso? ... 3.


Cdigos de Arduino .7.
Visual C# AWF 2015 .... 15.
Visual C# WPF 2015 ..... 34.
Visual Basic AWF 2015 ... 50.
Visual Basic WPF 2015 . 68.
Visual C++ CLR 2015 ... 84.
Vdeos .. 121.
Enlaces .. 123.
Autor .... 124.

Electrnica PIC | http://electronica-pic.blogspot.com.es 1


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

En esta ocasin se trata de leer las entradas digitales de Arduino UNO r3 y mostrar los
resultados con tu propia interfaz hecha bajo Visual Studio Community 2015 en cualquiera de
los lenguajes y tecnologas disponibles como Visual C#, Visual C++, Visual Basic .net, WPF C# y
WPF VB. No olvidar que tambin les vale Visual Studio Express 2015, en general es la versin
ms capada, lo que necesitamos en este momento lo incluye sin problemas.

Hay dos cdigos de ejemplo en Arduino. De los 4 interruptores como entradas digitales que
vamos a usar, muestra los resultados en Visual Studio en forma de cambiar los colores como
un panel de verde si est activado, rojo si est apagado, un label que indica palabra como
Activado, Desactivado y una imagen con pictureBox cuando muestra un Led en forma de
dibujo apagado y el otro encendido.

El otro ejemplo de Arduino se trata de comprobar los estados de los interruptores nada ms
encender Arduino o Resetearlo, a parte que muestra la informacin en el componente
richTextBox en Visual Studio.

Descargar Visual Studio Community 2015:

https://www.visualstudio.com/es-es/products/visual-studio-community-vs.aspx

Descargar Visual Studio Express 2015:

https://www.visualstudio.com/es-es/products/visual-studio-express-vs.aspx

Descargar Arduino IDE:

https://www.arduino.cc/en/Main/Software

Descargar cdigos fuentes de ejemplos de Visual Studio, Arduino e imgenes de los Led:

Enlace

Enlace

Electrnica PIC | http://electronica-pic.blogspot.com.es 2


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Qu puerto uso?
Para saber que puerto estamos usando con Arduino.
Entras desde Windows Inicio\Panel de control\Todos los elementos de Panel de
control\Sistema.
Luego pulsas Administrador de dispositivos.

Electrnica PIC | http://electronica-pic.blogspot.com.es 3


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

En mi caso usar el COM4, en tu caso puede ser diferente, as que para todo usars el que te
haya tocado.

Electrnica PIC | http://electronica-pic.blogspot.com.es 4


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Haz doble clic en Arduino UNO (COM4) para mostrar la ventana Propiedades: Arduino UNO
(COM4). En este caso para todo usar la configuracin que obtienes en la imagen, tanto para
Arduino UNO, en el Monitor Serie, en tu interfaz hecho con Visual Studio y en el cdigo de
Arduino.

Electrnica PIC | http://electronica-pic.blogspot.com.es 5


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Electrnica PIC | http://electronica-pic.blogspot.com.es 6


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Cdigos de Arduino
Ejemplo Arduino 1:

Entrada digital con Arduino y Visual Studio 2015. Muestra los estados de las entradas digitales
en componentes Panel, label y pictureBox de Visual Studio.

int estadoBoton=0; // Guardar el estado del botn HIGH o LOW.


int anteriorBoton=0;
char caracter;
String comando;
int flagMensaje=0;

void setup()

{
pinMode(13,OUTPUT); // Donde est el Led 13.
pinMode(8,INPUT); // Entrada digital donde est el pulsador.
Serial.begin(115200);
}

void loop()

{
estadoBoton=digitalRead(8); // Leer entrada digital nmero 8.

// Si el pulsador est pulsado, se enciende el Led 13 y


// enva comando HIGH por el puerto serie.

if(estadoBoton != anteriorBoton) // Comprueba si ha habido un cambio en el estado del


botn.

flagMensaje = 0; // Resetea la bandera a 0.


anteriorBoton = estadoBoton; // Guarda el estado actual del botn.

if (estadoBoton == HIGH && flagMensaje == 0) // Comprueba que el botn est pulsado y que
no se haya enviado el mensaje.

digitalWrite(13,HIGH);
Serial.write("ON");
delay(50);

if(flagMensaje == 0) // Si se envi el mensaje aumenta la variable a 1 para no enviarlo la


prxima vez.

flagMensaje++;

}
Electrnica PIC | http://electronica-pic.blogspot.com.es 7
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

// De lo contrario, Led 13 apagado y enva LOW al puerto serie.

else if(flagMensaje == 0) // Si el botn no est presionado y an no se enva el mensaje.

digitalWrite(13,LOW);
Serial.write("OFF");
delay(50);

if(flagMensaje == 0) // Si se envi el mensaje aumenta la variable en 1 para no enviarla la


prxima vez.

flagMensaje++;

Electrnica PIC | http://electronica-pic.blogspot.com.es 8


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo Arduino 2:

Muestra los datos o entradas digitales en el componente richTextBox de Visual Studio en


forma de texto, a parte si enciende o resetea fsicamente Arduino UNO, tambin muestra los
ltimos interruptores que tienes activados o no en ese momento. Si ejecutas a aplicacin, de
entrada no muestra nada, pulsas el botn Actualizar estados la interfaz que has creado con
Visual Studio para que te muestre los estados de las entradas digitales que tienes en ese
momento. En el Monitor Serie de Arduino IDE escribes el comando ACTUALIZAR, recibe la
misma orden para comprobar los estados.

byte estadoBoton1, estadoBoton2, estadoBoton3, estadoBoton4;


byte estadoBotonAnt1, estadoBotonAnt2, estadoBotonAnt3, estadoBotonAnt4;
char buffer[44];
char caracter;
String comando;

void setup()

pinMode(13,OUTPUT); // Donde est el Led 13.


pinMode(12,OUTPUT);
pinMode(11,OUTPUT);
pinMode(10,OUTPUT);
pinMode(8,INPUT); // Entrada digital 8.
pinMode(7,INPUT);
pinMode(6,INPUT);
pinMode(5,INPUT);
Serial.begin(115200);
leeEstado();
printEstado();

void loop() {

leeEstado();

if ((estadoBoton1 != estadoBotonAnt1) ||
(estadoBoton2 != estadoBotonAnt2) ||
(estadoBoton3 != estadoBotonAnt3) ||
(estadoBoton4 != estadoBotonAnt4))

printEstado();
delay(50);

Electrnica PIC | http://electronica-pic.blogspot.com.es 9


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

while (Serial.available() > 0)

{
caracter= Serial.read();
comando.concat(caracter);
delay(10);
}

if (comando.equals("ACTUALIZAR") == true)

printEstado();

// Limpiamos la cadena para volver a recibir el siguiente comando.

comando="";

// Funciones.

void leeEstado()

estadoBoton1 = digitalRead(8);
estadoBoton2 = digitalRead(7);
estadoBoton3 = digitalRead(6);
estadoBoton4 = digitalRead(5);

void printEstado(void)

digitalWrite(13,estadoBoton1);
digitalWrite(12,estadoBoton2);
digitalWrite(11,estadoBoton3);
digitalWrite(10,estadoBoton4);

sprintf(buffer,"%s %s %s %s",
estadoBoton1?"HIGH 1":"LOW 1",
estadoBoton2?"HIGH 2":"LOW 1",
estadoBoton3?"HIGH 3":"LOW 3",
estadoBoton4?"HIGH 4":"LOW 4");

Electrnica PIC | http://electronica-pic.blogspot.com.es 10


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Serial.println(buffer);
estadoBotonAnt1 = estadoBoton1;
estadoBotonAnt2 = estadoBoton2;
estadoBotonAnt3 = estadoBoton3;
estadoBotonAnt4 = estadoBoton4;

Electrnica PIC | http://electronica-pic.blogspot.com.es 11


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo Arduino 3:

Igual que en el anterior exceptuando el cambio de nombres de la salida de los datos hacia
visual Studio.

byte estadoBoton1,
estadoBoton2,
estadoBoton3,
estadoBoton4;
byte estadoBotonAnt1,
estadoBotonAnt2,
estadoBotonAnt3,
estadoBotonAnt4;
char buffer[36];
char caracter;
String comando;

void setup()

{
pinMode(13,OUTPUT); // Donde est el Led 13.
pinMode(12,OUTPUT);
pinMode(11,OUTPUT);
pinMode(10,OUTPUT);
pinMode(8,INPUT); // Entrada digital 8.
pinMode(7,INPUT);
pinMode(6,INPUT);
pinMode(5,INPUT);
Serial.begin(115200);
leeEstado();
printEstado();
}

void loop()
{
leeEstado();
if ((estadoBoton1 != estadoBotonAnt1) ||
(estadoBoton2 != estadoBotonAnt2) ||
(estadoBoton3 != estadoBotonAnt3) ||
(estadoBoton4 != estadoBotonAnt4))

printEstado();
delay(100);

Electrnica PIC | http://electronica-pic.blogspot.com.es 12


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

while (Serial.available() > 0)

caracter= Serial.read();
comando.concat(caracter);
delay(10);

if (comando.equals("ACTUALIZAR") == true)

printEstado();

// Limpiamos la cadena para volver a recibir el siguiente comando.

comando="";

// Funciones.

void leeEstado()

{
estadoBoton1 = digitalRead(8);
estadoBoton2 = digitalRead(7);
estadoBoton3 = digitalRead(6);
estadoBoton4 = digitalRead(5);

void printEstado(void)

digitalWrite(13,estadoBoton1);
digitalWrite(12,estadoBoton2);
digitalWrite(11,estadoBoton3);
digitalWrite(10,estadoBoton4);
sprintf(buffer,"%s %s %s %s",
estadoBoton1?"1=ON":"1=OFF",
estadoBoton2?"2=ON":"2=OFF",
estadoBoton3?"3=ON":"3=OFF",
estadoBoton4?"4=ON":"4=OFF");
Serial.print(buffer);
estadoBotonAnt1 = estadoBoton1;
estadoBotonAnt2 = estadoBoton2;
estadoBotonAnt3 = estadoBoton3;
estadoBotonAnt4 = estadoBoton4;

}
Electrnica PIC | http://electronica-pic.blogspot.com.es 13
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Electrnica PIC | http://electronica-pic.blogspot.com.es 14


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Visual C# AWF 2015

Electrnica PIC | http://electronica-pic.blogspot.com.es 15


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 1:

Este ejemplo corresponde al cdigo del Ejemplo 1 de Arduino.

Creamos un proyecto nuevo con Visual C#.

Selecciona Entorno clsico en Visual C#, Aplicacin de Windows Forms, he puesto como
nombre del proyecto en este caso Entrada_Arduino_AWF_1_CS, luego pulsar Aceptar.

Electrnica PIC | http://electronica-pic.blogspot.com.es 16


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Arrastramos al formulario los componentes que indica en el Cuadro de Herramientas.

Cambiamos las propiedades de cada componente o controles.

Panel:

Propiedad Cambie a
BorderStyle FixedSingle

Label:

Propiedad Cambie a
(Name) Label_Entrada
Text Leyendo...

PictureBox:

Propiedad Cambie a
(Name) pictureBox_Dibujo
SizeMode StretchImage

Electrnica PIC | http://electronica-pic.blogspot.com.es 17


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Seguimos en el componente PictureBox, pulsamos en la propiedad Image como indica abajo


para introducir dos imgenes de dos Led, encendido y apagado.

Electrnica PIC | http://electronica-pic.blogspot.com.es 18


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Se abre un cuadro llamado Seleccionar recurso en el cual podemos aadir las imgenes que
queramos.

Pulsamos el botn Importar y elegimos las imgenes de Leds que queramos, en este caso
selecciono el rojo apagado y encendido.

Electrnica PIC | http://electronica-pic.blogspot.com.es 19


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Queda guardado en recursos.

Pulsa Aceptar.

Dejar claro que en la propiedad SizeMode del PicturreBox le he puesto StretchImage par
redimensionar el dibujo o imagen al cuadro.

En cuanto al formulario principal, en la propiedad StartPosition se ha cambiado a CenterScreen


para cuando lo compilemos o lo ejecutemos salga en el centro de la pantalla.

Electrnica PIC | http://electronica-pic.blogspot.com.es 20


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Aade el componente SerialPort haciendo doble clic en l o arrastrndolo al formulario.

Electrnica PIC | http://electronica-pic.blogspot.com.es 21


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Cambiamos las propiedades indicadas abajo.

SerialPort:

Tanto en Visual Studio como Arduino UNO y Arduino IDE tienen que funcionar en el mismo
puerto y baudios, en mi caso es:

Propiedad Cambie a
BuadRate 115200
PortName COM4
StopBits Two

En tu caso puede ser diferente, tanto el puerto y los baudios el que desee.

Electrnica PIC | http://electronica-pic.blogspot.com.es 22


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Tener claro estas lneas al recibir datos desde Arduino como ON y OFF.

Electrnica PIC | http://electronica-pic.blogspot.com.es 23


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 1:

Cdigo fuente del Ejemplo 1 de Visual C# AWF.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO.Ports; // No olvidar.

namespace Entrada_Arduino_AWF_1_CS
{
public partial class Form1 : Form
{
// Utilizaremos un string como buffer de recepcin.
string Recibidos;

public Form1()
{
InitializeComponent();

if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}

serialPort1.DataReceived += new
SerialDataReceivedEventHandler(Recepcion);
}
}

// Al recibir datos.
private void Recepcion(object sender, SerialDataReceivedEventArgs e)
{
// Acumula los caracteres recibidos a nuestro 'buffer' (string).
Recibidos += serialPort1.ReadExisting();

// Invocar o llamar al proceso de tramas.


Invoke(new EventHandler(Actualizar));
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 24


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

// Procesar los datos recibidos en el bufer y extraer tramas completas.


private void Actualizar(object sender, EventArgs e)
{

switch (Recibidos)
{
case "ON":
panel1.BackColor = Color.Green;
label_Lectura.Text = "Activado";
pictureBox_Dibujo.Image =
Properties.Resources.Led_rojo_encendido;
Recibidos = "";
break;

case "OFF":
panel1.BackColor = Color.Red;
label_Lectura.Text = "Desactivado";
pictureBox_Dibujo.Image =
Properties.Resources.Led_rojo_apagado;
Recibidos = "";
break;
}
}

// Cuando cierre la aplicacin.


private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) // El puerto est abierto?
{
serialPort1.Close(); // Cerrar puerto.
}
}
}
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 25


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 2:

Este ejemplo corresponde al cdigo del Ejemplo 2 de Arduino.

Si has llegado aqu directamente, se recomienda leer paso a paso el primer ejemplo.

Creamos el proyecto nuevo al igual que el Ejemplo 1 y esta vez lo llamamos


Entrada_Arduino_WPF_2_CS, puedes poner el nombre que quieras del proyecto.

Electrnica PIC | http://electronica-pic.blogspot.com.es 26


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Cdigo fuente del Ejemplo 2 de Visual C# AWF.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO.Ports; // No olvidar.

namespace Entrada_Arduino_AWF_2_CS
{
public partial class Form1 : Form
{
// Utilizaremos un string como buffer de recepcin.
string Recibidos;

public Form1()
{
InitializeComponent();
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}

serialPort1.DataReceived += new
SerialDataReceivedEventHandler(Recepcion);
}
}
// Al recibir datos.
private void Recepcion(object sender, SerialDataReceivedEventArgs e)
{
// Acumula los caracteres recibidos a nuestro 'buffer' (string).
Recibidos += serialPort1.ReadExisting();

// Invocar o llamar al proceso de tramas.


Invoke(new EventHandler(Actualizar));
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 27


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

// Procesar los datos recibidos en el bufer y extraer tramas completas.


private void Actualizar(object sender, EventArgs e)
{

// Asignar el valor de la trama al richTextBox.


richTextBox1.Text = Recibidos + "\n";

// Selecciona la posicin final para leer los mensajes entrantes.


richTextBox1.SelectionStart = richTextBox1.Text.Length;

// Mantiene el scroll en la entrada de cada mensaje.


richTextBox1.ScrollToCaret();

private void Form1_FormClosing(object sender, FormClosingEventArgs e)


{
if (serialPort1.IsOpen) // El puerto est abierto?
{
serialPort1.Close(); // Puerto cerrado.
}
}

private void button_Actualizar_Click(object sender, EventArgs e)


{
Actualizar();
}

private void button_Limpiar_Click(object sender, EventArgs e)


{
richTextBox1.Clear(); // Limpiar contenido del richTextBox.
Recibidos = "";
}

void Actualizar()
{
byte[] mBuffer = Encoding.ASCII.GetBytes("ACTUALIZAR"); // Enva
comando ACTUALIZAR por el puerto.
serialPort1.Write(mBuffer, 0, mBuffer.Length);
}

private void Form1_Load(object sender, EventArgs e)


{
Actualizar();
}
}
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 28


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 3:

Este ejemplo corresponde al cdigo del Ejemplo 3 de Arduino.

Se trata en este caso unir los dos ejemplos de Visual Studio, las imgenes de los Leds y mostrar
mensajes en el richTextBox.

Se recomienda mirar el primer ejemplo para seguir bien la gua o entender el concepto si eres
muy novel.

Electrnica PIC | http://electronica-pic.blogspot.com.es 29


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Cdigo fuente del Ejemplo 3 de Visual C# AWF.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO.Ports; // No olvidar.

namespace Entrada_Arduino_AWF_3_CS
{
public partial class Form1 : Form
{
// Utilizaremos un string como buffer de recepcin.
string Recibidos;

public Form1()
{
InitializeComponent();

if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}

serialPort1.DataReceived += new
SerialDataReceivedEventHandler(Recepcion);
}
}
// Al recibir datos.
private void Recepcion(object sender, SerialDataReceivedEventArgs e)
{
// Acumula los caracteres recibidos a nuestro 'buffer' (string).
Recibidos += serialPort1.ReadExisting();

// Invocar o llamar al proceso de tramas.


Invoke(new EventHandler(Actualizar));
}

// Procesar los datos recibidos en el bufer y extraer tramas completas.


private void Actualizar(object sender, EventArgs e)
{

// Asignar el valor de la trama al richTextBox.


richTextBox1.Text += Recibidos;

// Selecciona la posicin final para leer los mensajes entrantes.


richTextBox1.SelectionStart = richTextBox1.Text.Length;

// Mantiene el scroll en la entrada de cada mensaje.


richTextBox1.ScrollToCaret();

Electrnica PIC | http://electronica-pic.blogspot.com.es 30


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

char[] Delimitador = { ' ', '\r', '\n' };

string[] Palabras = Recibidos.Split(Delimitador);

foreach (string Comandos in Palabras)


{
switch (Comandos)
{
case "1=ON":
pictureBox1.Image =
Properties.Resources.Led_rojo_encendido;
Recibidos = "";
break;

case "1=OFF":
pictureBox1.Image =
Properties.Resources.Led_rojo_apagado;
Recibidos = "";
break;

case "2=ON":
pictureBox2.Image =
Properties.Resources.Led_rojo_encendido;
Recibidos = "";
break;

case "2=OFF":
pictureBox2.Image =
Properties.Resources.Led_rojo_apagado;
Recibidos = "";
break;

case "3=ON":
pictureBox3.Image =
Properties.Resources.Led_rojo_encendido;
Recibidos = "";
break;

case "3=OFF":
pictureBox3.Image =
Properties.Resources.Led_rojo_apagado;
Recibidos = "";
break;

case "4=ON":
pictureBox4.Image =
Properties.Resources.Led_rojo_encendido;
Recibidos = "";
break;

case "4=OFF":
pictureBox4.Image =
Properties.Resources.Led_rojo_apagado;
Recibidos = "";
break;
}
}

richTextBox1.Text += " " + DateTime.Now.ToString() + "\r";


}

Electrnica PIC | http://electronica-pic.blogspot.com.es 31


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

private void Form1_FormClosing(object sender, FormClosingEventArgs e)


{
if (serialPort1.IsOpen) // El puerto est abierto?
{
serialPort1.Close(); // Puerto cerrado.
}
}

void Actualizar()
{
byte[] mBuffer = Encoding.ASCII.GetBytes("ACTUALIZAR"); // Enva
comando ACTUALIZAR por el puerto.
serialPort1.Write(mBuffer, 0, mBuffer.Length);
}

private void button_Actualizar_Click(object sender, EventArgs e)


{
Actualizar();
}

private void Form1_Load(object sender, EventArgs e)


{
Actualizar();
}

private void button2_Click(object sender, EventArgs e)


{
richTextBox1.Clear(); // Limpiar contenido del richTextBox.
Recibidos = "";
}
}
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 32


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Electrnica PIC | http://electronica-pic.blogspot.com.es 33


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Visual C# WPF 2015

Electrnica PIC | http://electronica-pic.blogspot.com.es 34


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Creamos un proyecto nuevo con Visual C#.

Como nombre en este caso lo he llamado Entrada_Arduino_WPF_1_CS.

Electrnica PIC | http://electronica-pic.blogspot.com.es 35


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Arrastramos tres componentes al formulario llamado Rectangle, label y Image.

Cambiamos las propiedades de cada componente o controles.

Rectangle:

Propiedades Cambie a
Nombre Rectangulo

Label:

Propiedades Cambie a
Nombre label_Leyendo
Content Leyendo

Image:

Propiedades Cambie a
Nombre Image
Source Led rojo apagado.png

Electrnica PIC | http://electronica-pic.blogspot.com.es 36


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Seguimos en el componente image, pulsamos en la propiedad Image como indica abajo,


Proyecto Agregar elemento existente

Podemos seleccionar las imgenes que queremos, en este caso he elegido el Led apagado y el
otro encendido de color rojo. Para finalizar, pulsa el botn Agregar.

Electrnica PIC | http://electronica-pic.blogspot.com.es 37


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

En la propiedad Source, eliges el Led rojo apagado, si lo deseas, puede escoger el verde, pero
que sea apagado.

Electrnica PIC | http://electronica-pic.blogspot.com.es 38


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Tener claro estas lneas al recibir datos desde Arduino como ON y OFF.

Electrnica PIC | http://electronica-pic.blogspot.com.es 39


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 1:

Cdigo fuente del Ejemplo 1 de Visual C# WPF.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO.Ports; // No olvidar.


using System.Threading;

namespace Entrada_Arduino_WPF_1_CS
{
/// <summary>
/// Lgica de interaccin para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
// Utilizaremos un string como buffer de recepcin.
string Recibidos;
SerialPort serialPort1 = new SerialPort();

public MainWindow()
{
InitializeComponent();

// Configuramos el puerto serie.


serialPort1.BaudRate = 115200; // Baudios, tiene que ser el mismo que
Arduino.
serialPort1.PortName = "COM4"; // Elegijos el mismo puerto que de
Arduino.
serialPort1.Parity = Parity.None; // Nada de paridad.
serialPort1.DataBits = 8; // 8 bits.
serialPort1.StopBits = StopBits.Two; // Recomendado con 2 bits de
Stop o parada.

// Abrir y mantener abierto el puerto serie mientras se ejecute la


aplicacin.
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 40


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

// Ejecutar la funcin Recepcin por disparo del evento DataReived!


serialPort1.DataReceived += Recepcion;
}

private void Recepcion(object sender, SerialDataReceivedEventArgs e)


{
// Acumular los caracteres recibidos a nuestro "buffer" (string).
Recibidos += serialPort1.ReadExisting();

// Invocar o llamar al proceso de tramas.


this.Dispatcher.Invoke(Actualizar);
}

// Procesar los datos recibidos en el buffer y extraer tramas completas.


private void Actualizar()
{
var doc = new FlowDocument();
doc.Blocks.Add(new Paragraph(new Run(Recibidos)));

switch(Recibidos)
{
case "ON":
image.Source = (new BitmapImage(new Uri("Led rojo
encendido.png", UriKind.Relative)));
label_Leyendo.Content = "Encendido.";
Rectangulo.Fill = new SolidColorBrush(Colors.Green);
Recibidos = ""; // Limpiar.
break;

case "OFF":
image.Source = (new BitmapImage(new Uri("Led rojo
apagado.png", UriKind.Relative)));
label_Leyendo.Content = "Apagado.";
Rectangulo.Fill = new SolidColorBrush(Colors.Red);
Recibidos = ""; // Limpiar.
break;
}
}

private void Form_principal_Closing(object sender,


System.ComponentModel.CancelEventArgs e)
{
if (serialPort1.IsOpen) // El puerto est abierto?
{
serialPort1.Close(); // Cerrar puerto.
}

}
}
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 41


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Este ejemplo corresponde al cdigo del Ejemplo 2 de Arduino.

Si has llegado aqu directamente, se recomienda leer paso a paso el primer ejemplo.

Creamos el proyecto nuevo al igual que el Ejemplo 1 y esta vez lo llamamos


Entrada_Arduino_WPF_2_CS, puedes poner el nombre que quieras del proyecto.

Electrnica PIC | http://electronica-pic.blogspot.com.es 42


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 2:

Cdigo fuente del Ejemplo 2 de Visual C# WPF.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO.Ports; // No olvidar.


using System.Threading;

namespace Entrada_Arduino_WPF_2_CS
{
/// <summary>
/// Lgica de interaccin para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
// Utilizaremos un string como buffer de recepcin.
string Recibidos;
SerialPort serialPort1 = new SerialPort();

public MainWindow()
{
InitializeComponent();

// Configuramos el puerto serie.


serialPort1.BaudRate = 115200; // Baudios, tiene que ser el mismo que
Arduino.
serialPort1.PortName = "COM4"; // Elegijos el mismo puerto que de
Arduino.
serialPort1.Parity = Parity.None; // Nada de paridad.
serialPort1.DataBits = 8; // 8 bits.
serialPort1.StopBits = StopBits.Two; // Recomendado con 2 bits de
Stop o parada.

// Abrir y mantener abierto el puerto serie mientras se ejecute la


aplicacin.
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 43


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

// Ejecutar la funcin Recepcin por disparo del evento DataReived!


serialPort1.DataReceived += Recepcion;
}

private void Recepcion(object sender, SerialDataReceivedEventArgs e)


{
// Acumular los caracteres recibidos a nuestro "buffer" (string).
Recibidos += serialPort1.ReadExisting();

// Invocar o llamar al proceso de tramas.


this.Dispatcher.Invoke(Actualizar);
}

// Procesar los datos recibidos en el buffer y extraer tramas completas.


private void Actualizar()
{
// Muestra el scroll vertical.
richTextBox.VerticalScrollBarVisibility =
ScrollBarVisibility.Visible;

// Asignar el valor de la trama al richTextBox.


var doc = new FlowDocument();
doc.Blocks.Add(new Paragraph(new Run(Recibidos +=
Environment.NewLine)));
richTextBox.Document = doc;

// // Mantiene el scroll en la entrada de cada mensaje.


richTextBox.ScrollToEnd();
}

void Actualizar_estados()
{
byte[] miBuffer = Encoding.ASCII.GetBytes("ACTUALIZAR"); // Enva
comando ACTUALIZAR por el puerto.
serialPort1.Write(miBuffer, 0, miBuffer.Length);
}

private void button_Actualizar_estados_Click(object sender,


RoutedEventArgs e)
{
Actualizar_estados();
}

private void button_Limpiar_Click(object sender, RoutedEventArgs e)


{
richTextBox.Document.Blocks.Clear(); // Limpiar contenido del
richTextBox.
Recibidos = ""; // Limpiar variable.
}

// Desde que cierres el programa, cierra el puerto.


private void Form_Principal_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
if (serialPort1.IsOpen) // El puerto est abierto?
{
serialPort1.Close(); // Cerrar puerto.
}
}
}
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 44


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 3:

Este ejemplo corresponde al cdigo del Ejemplo 3 de Arduino.

Se trata en este caso unir los dos ejemplos de Visual Studio, las imgenes de los Leds y mostrar
mensajes en el richTextBox.

Se recomienda mirar el primer ejemplo para seguir bien la gua o entender el concepto si eres
muy novel.

Electrnica PIC | http://electronica-pic.blogspot.com.es 45


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 3:

Cdigo fuente del Ejemplo 3 de Visual C# WPF.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO.Ports; // No olvidar.


using System.Threading;

namespace Entrada_Arduino_WPF_3_CS
{
/// <summary>
/// Lgica de interaccin para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{

// Utilizaremos un string como buffer de recepcin.


string Recibidos;
SerialPort serialPort1 = new SerialPort();

public MainWindow()
{
InitializeComponent();

// Configuramos el puerto serie.


serialPort1.BaudRate = 115200; // Baudios, tiene que ser el mismo que
Arduino.
serialPort1.PortName = "COM4"; // Elegijos el mismo puerto que de
Arduino.
serialPort1.Parity = Parity.None; // Nada de paridad.
serialPort1.DataBits = 8; // 8 bits.
serialPort1.StopBits = StopBits.Two; // Recomendado con 2 bits de
Stop o parada.

// Abrir y mantener abierto el puerto serie mientras se ejecute la


aplicacin.
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 46


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

// Ejecutar la funcin Recepcin por disparo del evento DataReived!


serialPort1.DataReceived += Recepcion;
}

private void Recepcion(object sender, SerialDataReceivedEventArgs e)


{
// Acumular los caracteres recibidos a nuestro "buffer" (string).
Recibidos += serialPort1.ReadExisting();

// Invocar o llamar al proceso de tramas.


this.Dispatcher.Invoke(Actualizar);
}

// Procesar los datos recibidos en el buffer y extraer tramas completas.


private void Actualizar()
{
// Muestra el scroll vertical.
richTextBox.VerticalScrollBarVisibility =
ScrollBarVisibility.Visible;

// Asignar el valor de la trama al richTextBox.


var doc = new FlowDocument();
doc.Blocks.Add(new Paragraph(new Run(Recibidos +=
Environment.NewLine)));
richTextBox.Document = doc;

// // Mantiene el scroll en la entrada de cada mensaje.


richTextBox.ScrollToEnd();

char[] Delimitador = { ' ', '\r', '\n' };

string[] Palabras = Recibidos.Split(Delimitador);

foreach (string Comandos in Palabras)


{
switch (Comandos)
{
case "1=ON":
image_1.Source = (new BitmapImage(new Uri("Led rojo
encendido.png", UriKind.Relative)));
Recibidos = ""; // Limpiar.
break; ;

case "1=OFF":
image_1.Source = (new BitmapImage(new Uri("Led rojo
apagado.png", UriKind.Relative)));
Recibidos = ""; // Limpiar.
break;

case "2=ON":
image_2.Source = (new BitmapImage(new Uri("Led rojo
encendido.png", UriKind.Relative)));
Recibidos = ""; // Limpiar.
break;

case "2=OFF":
image_2.Source = (new BitmapImage(new Uri("Led rojo
apagado.png", UriKind.Relative)));
Recibidos = ""; // Limpiar.
break;

Electrnica PIC | http://electronica-pic.blogspot.com.es 47


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

case "3=ON":
image_3.Source = (new BitmapImage(new Uri("Led rojo
encendido.png", UriKind.Relative)));
Recibidos = ""; // Limpiar.
break;

case "3=OFF":
image_3.Source = (new BitmapImage(new Uri("Led rojo
apagado.png", UriKind.Relative)));
Recibidos = ""; // Limpiar.
break;

case "4=ON":
image_4.Source = (new BitmapImage(new Uri("Led rojo
encendido.png", UriKind.Relative)));
Recibidos = ""; // Limpiar.
break;

case "4=OFF":
image_4.Source = (new BitmapImage(new Uri("Led rojo
apagado.png", UriKind.Relative)));
Recibidos = ""; // Limpiar.
break;
}
}
}

void Actualizar_estados()
{
byte[] miBuffer = Encoding.ASCII.GetBytes("ACTUALIZAR"); // Enva
comando ACTUALIZAR por el puerto.
serialPort1.Write(miBuffer, 0, miBuffer.Length);
}

private void button_Actualizar_estados_Click(object sender,


RoutedEventArgs e)
{
Actualizar_estados();
}

private void button_Limpiar_Click(object sender, RoutedEventArgs e)


{
richTextBox.Document.Blocks.Clear(); // Limpiar contenido del
richTextBox.
Recibidos = ""; // Limpiar variable.
}

private void Form_Principal_Closing(object sender,


System.ComponentModel.CancelEventArgs e)
{
if (serialPort1.IsOpen) // El puerto est abierto?
{
serialPort1.Close(); // Cerrar puerto.
}
}
}
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 48


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Electrnica PIC | http://electronica-pic.blogspot.com.es 49


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Visual Basic AWF 2015

Electrnica PIC | http://electronica-pic.blogspot.com.es 50


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 1:

Este ejemplo corresponde al cdigo del Ejemplo 1 de Arduino.

Creamos un proyecto nuevo con Visual Basic.

Selecciona Entorno clsico en Visual Basic, Aplicacin de Windows Forms, he puesto como
nombre del proyecto en este caso Entrada_Arduino_AWF_1_VB, luego pulsar Aceptar.

Electrnica PIC | http://electronica-pic.blogspot.com.es 51


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Arrastramos al formulario los componentes que indica en el Cuadro de Herramientas.

Cambiamos las propiedades de cada componente o controles.

Panel:

Propiedad Cambie a
BorderStyle FixedSingle

Label:

Propiedad Cambie a
(Name) Label_Entrada
Text Leyendo...

PictureBox:

Propiedad Cambie a
(Name) pictureBox_Dibujo
SizeMode StretchImage

Electrnica PIC | http://electronica-pic.blogspot.com.es 52


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Seguimos en el componente PictureBox, pulsamos en la propiedad Image como indica abajo


para introducir dos imgenes de dos Led, encendido y apagado.

Electrnica PIC | http://electronica-pic.blogspot.com.es 53


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Se abre un cuadro llamado Seleccionar recurso en el cual podemos aadir las imgenes que
queramos.

Pulsamos el botn Importar y elegimos las imgenes de Leds que queramos, en este caso
selecciono el rojo apagado y encendido.

Electrnica PIC | http://electronica-pic.blogspot.com.es 54


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Queda guardado en recursos.

Pulsa Aceptar.

Dejar claro que en la propiedad SizeMode del PicturreBox le he puesto StretchImage par
redimensionar el dibujo o imagen al cuadro.

En cuanto al formulario principal, en la propiedad StartPosition se ha cambiado a CenterScreen


para cuando lo compilemos o lo ejecutemos salga en el centro de la pantalla.

Electrnica PIC | http://electronica-pic.blogspot.com.es 55


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Aade el componente SerialPort haciendo doble clic en l o arrastrndolo al formulario.

Electrnica PIC | http://electronica-pic.blogspot.com.es 56


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Cambiamos las propiedades indicadas abajo.

SerialPort:

Tanto en Visual Studio como Arduino UNO y Arduino IDE tienen que funcionar en el mismo
puerto y baudios, en mi caso es:

Propiedad Cambie a
BuadRate 115200
PortName COM4
StopBits Two

En tu caso puede ser diferente, tanto el puerto y los baudios el que desee.

Electrnica PIC | http://electronica-pic.blogspot.com.es 57


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Tener claro estas lneas al recibir datos desde Arduino como ON y OFF.

Electrnica PIC | http://electronica-pic.blogspot.com.es 58


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 1:

Cdigo fuente del Ejemplo 1 de Visual Basic AWF.


Imports System.IO.Ports ' No olvidar.
Imports System.Threading

Public Class Form1


' Utilizaremos un string como buffer de recepcin.
Private Recibidos As String

Public Sub New()


InitializeComponent()

If Not SerialPort1.IsOpen Then


Try
SerialPort1.Open()
Catch ex As System.Exception
MessageBox.Show(ex.ToString())
End Try

'Ejecutar la funcin Recepcion por disparo del evento DataReceived.


AddHandler SerialPort1.DataReceived, AddressOf Recepcion

End If
End Sub

' Al recibir datos.


Private Sub Recepcion(sender As Object, e As SerialDataReceivedEventArgs)
' Acumula los caracteres recibidos a nuestro 'buffer' (string).
Recibidos += SerialPort1.ReadExisting()

' Invocar o llamar al proceso de tramas.


Invoke(New EventHandler(AddressOf Actualizar))
End Sub

' Procesar los datos recibidos en el bufer y extraer tramas completas.


Private Sub Actualizar(sender As Object, e As EventArgs)

Select Case Recibidos


Case "ON"
Panel1.BackColor = Color.Green
Label_Leyendo.Text = "Activado"
PictureBox_Dibujo.Image = My.Resources.Led_rojo_encendido
Recibidos = ""
Exit Select

Case "OFF"
Panel1.BackColor = Color.Red
Label_Leyendo.Text = "Desactivado"
PictureBox_Dibujo.Image = My.Resources.Led_rojo_apagado
Recibidos = ""
Exit Select
End Select
End Sub

End Class

Electrnica PIC | http://electronica-pic.blogspot.com.es 59


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 2:

Este ejemplo corresponde al cdigo del Ejemplo 2 de Arduino.

Si has llegado aqu directamente, se recomienda leer paso a paso el primer ejemplo.

Creamos el proyecto nuevo al igual que el Ejemplo 1 y esta vez lo llamamos


Entrada_Arduino_AWF_2_VS, puedes poner el nombre que quieras del proyecto.

Electrnica PIC | http://electronica-pic.blogspot.com.es 60


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Imports System.IO.Ports ' No olvidar.


Imports System.Text
Imports System.Threading

Public Class Form1


' Utilizaremos un string como buffer de recepcin.
Private Recibidos As String

Public Sub New()


InitializeComponent()

If Not SerialPort1.IsOpen Then


Try
SerialPort1.Open()
Catch ex As System.Exception
MessageBox.Show(ex.ToString())
End Try

'Ejecutar la funcin Recepcion por disparo del evento DataReceived.


AddHandler SerialPort1.DataReceived, AddressOf Recepcion

End If
End Sub

' Al recibir datos.


Private Sub Recepcion(sender As Object, e As SerialDataReceivedEventArgs)
' Acumula los caracteres recibidos a nuestro 'buffer' (string).
Recibidos += SerialPort1.ReadExisting()

' Invocar o llamar al proceso de tramas.


Invoke(New EventHandler(AddressOf Actualizar))
End Sub

' Procesar los datos recibidos en el bufer y extraer tramas completas.


Private Sub Actualizar(sender As Object, e As EventArgs)

' Asignar el valor de la trama al richTextBox.


RichTextBox1.Text = Recibidos + vbLf

' Selecciona la posicin final para leer los mensajes entrantes.


RichTextBox1.SelectionStart = RichTextBox1.Text.Length

' Mantiene el scroll en la entrada de cada mensaje.


RichTextBox1.ScrollToCaret()

End Sub

Private Sub Actualizar()


Dim mBuffer As Byte() = Encoding.ASCII.GetBytes("ACTUALIZAR")
' Enva comando ACTUALIZAR por el puerto.
SerialPort1.Write(mBuffer, 0, mBuffer.Length)
End Sub

Private Sub Button_Actualizar_Click(sender As Object, e As EventArgs) Handles


Button_Actualizar.Click
Actualizar()
End Sub

Electrnica PIC | http://electronica-pic.blogspot.com.es 61


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Private Sub Button_Limpiar_Click(sender As Object, e As EventArgs) Handles


Button_Limpiar.Click
RichTextBox1.Clear() ' Limpiar contenido del richTextBox.
Recibidos = ""
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


Actualizar()
End Sub
End Class

Electrnica PIC | http://electronica-pic.blogspot.com.es 62


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 3:

Este ejemplo corresponde al cdigo del Ejemplo 3 de Arduino.

Se trata en este caso unir los dos ejemplos de Visual Studio, las imgenes de los Leds y mostrar
mensajes en el richTextBox.

Se recomienda mirar el primer ejemplo para seguir bien la gua o entender el concepto si eres
muy novel.

Electrnica PIC | http://electronica-pic.blogspot.com.es 63


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Imports System.IO.Ports ' No olvidar.


Imports System.Text
Imports System.Threading

Public Class Form1


' Utilizaremos un string como buffer de recepcin.
Private Recibidos As String

Public Sub New()


InitializeComponent()

If Not SerialPort1.IsOpen Then


Try
SerialPort1.Open()
Catch ex As System.Exception
MessageBox.Show(ex.ToString())
End Try

'Ejecutar la funcin Recepcion por disparo del evento DataReceived.


AddHandler SerialPort1.DataReceived, AddressOf Recepcion

End If
End Sub

' Al recibir datos.


Private Sub Recepcion(sender As Object, e As SerialDataReceivedEventArgs)
' Acumula los caracteres recibidos a nuestro 'buffer' (string).
Recibidos += SerialPort1.ReadExisting()

' Invocar o llamar al proceso de tramas.


Invoke(New EventHandler(AddressOf Actualizar))
End Sub

' Procesar los datos recibidos en el bufer y extraer tramas completas.


Private Sub Actualizar(sender As Object, e As EventArgs)

' Asignar el valor de la trama al richTextBox.


RichTextBox1.Text = Recibidos + vbLf

' Selecciona la posicin final para leer los mensajes entrantes.


RichTextBox1.SelectionStart = RichTextBox1.Text.Length

' Mantiene el scroll en la entrada de cada mensaje.


RichTextBox1.ScrollToCaret()

Dim Delimitador As Char() = {" "c, ControlChars.Cr, ControlChars.Lf}

Dim Palabras As String() = Recibidos.Split(Delimitador)

Electrnica PIC | http://electronica-pic.blogspot.com.es 64


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

For Each Comandos As String In Palabras


Select Case Comandos
Case "1=ON"
PictureBox1.Image = My.Resources.Led_rojo_encendido
Recibidos = ""
Exit Select

Case "1=OFF"
PictureBox1.Image = My.Resources.Led_rojo_apagado
Recibidos = ""
Exit Select

Case "2=ON"
PictureBox2.Image = My.Resources.Led_rojo_encendido
Recibidos = ""
Exit Select

Case "2=OFF"
PictureBox2.Image = My.Resources.Led_rojo_apagado
Recibidos = ""
Exit Select

Case "3=ON"
PictureBox3.Image = My.Resources.Led_rojo_encendido
Recibidos = ""
Exit Select

Case "3=OFF"
PictureBox3.Image = My.Resources.Led_rojo_apagado
Recibidos = ""
Exit Select

Case "4=ON"
PictureBox4.Image = My.Resources.Led_rojo_encendido
Recibidos = ""
Exit Select

Case "4=OFF"
PictureBox4.Image = My.Resources.Led_rojo_apagado
Recibidos = ""
Exit Select
End Select
Next

RichTextBox1.Text += " " + DateTime.Now.ToString() + vbCr

End Sub

Private Sub Actualizar()


Dim mBuffer As Byte() = Encoding.ASCII.GetBytes("ACTUALIZAR") ' Enva
comando ACTUALIZAR por el puerto.
SerialPort1.Write(mBuffer, 0, mBuffer.Length)
End Sub

Private Sub Button_Actualizar_Click(sender As Object, e As EventArgs) Handles


Button_Actualizar.Click
Actualizar()
End Sub

Private Sub Button_Limpiar_Click(sender As Object, e As EventArgs) Handles


Button_Limpiar.Click
RichTextBox1.Clear() ' Limpiar contenido del richTextBox.

Electrnica PIC | http://electronica-pic.blogspot.com.es 65


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Recibidos = ""
End Sub

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs)


Handles MyBase.FormClosing
If SerialPort1.IsOpen Then ' El puerto est abierto?
SerialPort1.Close() ' Puerto cerrado.
End If
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


Actualizar()
End Sub
End Class

Electrnica PIC | http://electronica-pic.blogspot.com.es 66


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Electrnica PIC | http://electronica-pic.blogspot.com.es 67


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Visual Basic WPF 2015

Electrnica PIC | http://electronica-pic.blogspot.com.es 68


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Creamos un proyecto nuevo con Visual Basic.

Como nombre en este caso lo he llamado Entrada_Arduino_WPF_1_VB.

Electrnica PIC | http://electronica-pic.blogspot.com.es 69


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Arrastramos tres componentes al formulario llamado Rectangle, label y Image.

Cambiamos las propiedades de cada componente o controles.

Rectangle:

Propiedades Cambie a
Nombre Rectangulo

Label:

Propiedades Cambie a
Nombre label_Leyendo
Content Leyendo

Image:

Propiedades Cambie a
Nombre Image
Source Led rojo apagado.png

Electrnica PIC | http://electronica-pic.blogspot.com.es 70


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Seguimos en el componente image, pulsamos en la propiedad Image como indica abajo,


Proyecto Agregar elemento existente

Podemos seleccionar las imgenes que queremos, en este caso he elegido el Led apagado y el
otro encendido de color rojo. Para finalizar, pulsa el botn Agregar.

En la propiedad Source, eliges el Led rojo apagado, si lo deseas, puede escoger el verde, pero
que sea apagado.
Electrnica PIC | http://electronica-pic.blogspot.com.es 71
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Electrnica PIC | http://electronica-pic.blogspot.com.es 72


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Tener claro estas lneas al recibir datos desde Arduino como ON y OFF.

Electrnica PIC | http://electronica-pic.blogspot.com.es 73


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 1:

Cdigo fuente del Ejemplo 1 de Visual Basic WPF.


Imports System.IO.Ports ' No olvidar.
Imports System.Text ' No olvidar.

Class MainWindow
' Utilizaremos un string como buffer de recepcin.
Dim Recibidos As String
' Creamos un objeto sdel puerto serie.
Dim serialPort1 As New SerialPort()

Private Sub Form_Principal_Loaded(sender As Object, e As RoutedEventArgs)


Handles Form_Principal.Loaded
' Configuramos el puerto serie.
serialPort1.BaudRate = 115200 ' Baudios, tiene que ser el mismo que
Arduino UNO.
serialPort1.PortName = "COM4" ' Elegimos el COM4 igual que Arduino en mi
caso.
serialPort1.Parity = Parity.None ' Nada de paridad.
serialPort1.DataBits = 8 ' 8 bits.
serialPort1.StopBits = StopBits.Two ' Funciona mejor con 2 bits de Stop.

' Abrir puerto mientras se ejecute la aplicacin.


If Not serialPort1.IsOpen Then
Try
serialPort1.Open()
Catch ex As System.Exception
MessageBox.Show(ex.ToString())

End Try
End If
' Ejecutar la funcin Recepcin por disparo del evento DataReived!
AddHandler serialPort1.DataReceived, AddressOf Recepcion
End Sub

Private Sub Recepcion(sender As Object, e As SerialDataReceivedEventArgs)


' Acumular los caracteres recibidos a nuestro "buffer" (string).
Recibidos += serialPort1.ReadExisting()

' Invocar o llamar al proceso de tramas.


Me.Dispatcher.Invoke(AddressOf Actualizar)
End Sub

' Procesar los datos recibidos en el buffer y extraer tramas completas.


Private Sub Actualizar()
Dim doc = New FlowDocument()
doc.Blocks.Add(New Paragraph(New Run(Recibidos)))

Select Case Recibidos


Case "ON"
image.Source = (New BitmapImage(New Uri("Led rojo encendido.png",
UriKind.Relative)))
label_Leyendo.Content = "Encendido."
Rectangulo.Fill = New SolidColorBrush(Colors.Green)
Recibidos = "" ' Limpiar.
Exit Select

Case "OFF"
image.Source = (New BitmapImage(New Uri("Led rojo apagado.png",
UriKind.Relative)))

Electrnica PIC | http://electronica-pic.blogspot.com.es 74


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

label_Leyendo.Content = "Apagado."
Rectangulo.Fill = New SolidColorBrush(Colors.Red)
Recibidos = "" ' Limpiar.
Exit Select
End Select
End Sub

' Desde que cierres el programa, cierra el puerto.


Private Sub Form_Principal_Closing(sender As Object, e As
ComponentModel.CancelEventArgs) Handles Form_Principal.Closing
If serialPort1.IsOpen Then ' El puerto est abierto?
serialPort1.Close() ' Cerrar puerto.
End If
End Sub
End Class

Electrnica PIC | http://electronica-pic.blogspot.com.es 75


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Este ejemplo corresponde al cdigo del Ejemplo 2 de Arduino.

Si has llegado aqu directamente, se recomienda leer paso a paso el primer ejemplo.

Creamos el proyecto nuevo al igual que el Ejemplo 1 y esta vez lo llamamos


Entrada_Arduino_WPF_2_VB, puedes poner el nombre que quieras del proyecto.

Electrnica PIC | http://electronica-pic.blogspot.com.es 76


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 2:

Cdigo fuente del Ejemplo 2 de Visual Basic WPF.


Imports System.IO.Ports ' No olvidar.
Imports System.Text ' No olvidar.
Imports System.Threading ' No olvidar.

Class MainWindow
' Utilizaremos un string como buffer de recepcin.
Dim Recibidos As String
' Creamos un objeto sdel puerto serie.
Dim serialPort1 As New SerialPort()

Private Sub Form_Principal_Loaded(sender As Object, e As RoutedEventArgs)


Handles Form_Principal.Loaded
' Configuramos el puerto serie.
serialPort1.BaudRate = 115200 ' Baudios, tiene que ser el mismo que
Arduino UNO.
serialPort1.PortName = "COM4" ' Elegimos el COM4 igual que Arduino en mi
caso.
serialPort1.Parity = Parity.None ' Nada de paridad.
serialPort1.DataBits = 8 ' 8 bits.
serialPort1.StopBits = StopBits.Two ' Funciona mejor con 2 bits de Stop.

' Abrir puerto mientras se ejecute la aplicacin.


If Not serialPort1.IsOpen Then
Try
serialPort1.Open()
Catch ex As System.Exception
MessageBox.Show(ex.ToString())

End Try
End If
' Ejecutar la funcin Recepcin por disparo del evento DataReived!
AddHandler serialPort1.DataReceived, AddressOf Recepcion
End Sub

Private Sub Recepcion(sender As Object, e As SerialDataReceivedEventArgs)


' Acumular los caracteres recibidos a nuestro "buffer" (string).
Recibidos += serialPort1.ReadExisting()

' Invocar o llamar al proceso de tramas.


Me.Dispatcher.Invoke(AddressOf Actualizar)
End Sub

' Procesar los datos recibidos en el buffer y extraer tramas completas.


Private Sub Actualizar()
' Muestra el scroll vertical.
richTextBox.VerticalScrollBarVisibility = ScrollBarVisibility.Visible

' Asignar el valor de la trama al richTextBox.


Dim doc = New FlowDocument()
doc.Blocks.Add(New Paragraph(New Run(Recibidos + Environment.NewLine)))
richTextBox.Document = doc

' // Mantiene el scroll en la entrada de cada mensaje.


richTextBox.ScrollToEnd()
End Sub

Electrnica PIC | http://electronica-pic.blogspot.com.es 77


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Private Sub Actualizar_estados()


Dim miBuffer As Byte() = Encoding.ASCII.GetBytes("ACTUALIZAR")
' Enva comando ACTUALIZAR por el puerto.
serialPort1.Write(miBuffer, 0, miBuffer.Length)
End Sub

Private Sub button_Actualizar_estados_Click(sender As Object, e As


RoutedEventArgs) Handles button_Actualizar_estados.Click
Actualizar_estados()
End Sub

Private Sub button_Limpiar_Click(sender As Object, e As RoutedEventArgs)


Handles button_Limpiar.Click
richTextBox.Document.Blocks.Clear() ' Limpiar contenido del richTextBox.
Recibidos = "" ' Limpiar variable.
End Sub

' Desde que cierres el programa, cierra el puerto.


Private Sub Form_Principal_Closing(sender As Object, e As
ComponentModel.CancelEventArgs) Handles Form_Principal.Closing
If serialPort1.IsOpen Then ' El puerto est abierto?
serialPort1.Close() ' Cerrar puerto.
End If
End Sub
End Class

Electrnica PIC | http://electronica-pic.blogspot.com.es 78


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 3:

Este ejemplo corresponde al cdigo del Ejemplo 3 de Arduino.

Se trata en este caso unir los dos ejemplos de Visual Studio, las imgenes de los Leds y mostrar
mensajes en el richTextBox.

Se recomienda mirar el primer ejemplo para seguir bien la gua o entender el concepto si eres
muy novel.

Electrnica PIC | http://electronica-pic.blogspot.com.es 79


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 3:

Cdigo fuente del Ejemplo 3 de Visual Basic WPF.


Imports System.IO.Ports ' No olvidar.
Imports System.Text ' No olvidar.
Imports System.Threading ' No olvidar.

Class MainWindow
' Utilizaremos un string como buffer de recepcin.
Dim Recibidos As String
' Creamos un objeto sdel puerto serie.
Dim serialPort1 As New SerialPort()

Private Sub Form_Principal_Loaded(sender As Object, e As RoutedEventArgs)


Handles Form_Principal.Loaded
' Configuramos el puerto serie.
serialPort1.BaudRate = 115200 ' Baudios, tiene que ser el mismo que
Arduino UNO.
serialPort1.PortName = "COM4" ' Elegimos el COM4 igual que Arduino en mi
caso.
serialPort1.Parity = Parity.None ' Nada de paridad.
serialPort1.DataBits = 8 ' 8 bits.
serialPort1.StopBits = StopBits.Two ' Funciona mejor con 2 bits de Stop.

' Abrir puerto mientras se ejecute la aplicacin.


If Not serialPort1.IsOpen Then
Try
serialPort1.Open()
Catch ex As System.Exception
MessageBox.Show(ex.ToString())

End Try
End If
' Ejecutar la funcin Recepcin por disparo del evento DataReived!
AddHandler serialPort1.DataReceived, AddressOf Recepcion
End Sub

Private Sub Recepcion(sender As Object, e As SerialDataReceivedEventArgs)


' Acumular los caracteres recibidos a nuestro "buffer" (string).
Recibidos += serialPort1.ReadExisting()

' Invocar o llamar al proceso de tramas.


Me.Dispatcher.Invoke(AddressOf Actualizar)
End Sub

' Procesar los datos recibidos en el buffer y extraer tramas completas.


Private Sub Actualizar()
' Muestra el scroll vertical.
richTextBox.VerticalScrollBarVisibility = ScrollBarVisibility.Visible

' Asignar el valor de la trama al richTextBox.


Dim doc = New FlowDocument()
doc.Blocks.Add(New Paragraph(New Run(Recibidos + Environment.NewLine)))
richTextBox.Document = doc

' // Mantiene el scroll en la entrada de cada mensaje.


richTextBox.ScrollToEnd()

Dim Delimitador As Char() = {" "c, ControlChars.Cr, ControlChars.Lf}

Electrnica PIC | http://electronica-pic.blogspot.com.es 80


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Dim Palabras As String() = Recibidos.Split(Delimitador)

For Each Comandos As String In Palabras


Select Case Comandos
Case "1=ON"
image_1.Source = (New BitmapImage(New Uri("Led rojo
encendido.png", UriKind.Relative)))
Recibidos = "" ' Limpiar.
Exit Select

Case "1=OFF"
image_1.Source = (New BitmapImage(New Uri("Led rojo
apagado.png", UriKind.Relative)))
Recibidos = "" ' Limpiar.
Exit Select

Case "2=ON"
image_2.Source = (New BitmapImage(New Uri("Led rojo
encendido.png", UriKind.Relative)))
Recibidos = "" ' Limpiar.
Exit Select

Case "2=OFF"
image_2.Source = (New BitmapImage(New Uri("Led rojo
apagado.png", UriKind.Relative)))
Recibidos = "" ' Limpiar.
Exit Select

Case "3=ON"
image_3.Source = (New BitmapImage(New Uri("Led rojo
encendido.png", UriKind.Relative)))
Recibidos = "" ' Limpiar.
Exit Select

Case "3=OFF"
image_3.Source = (New BitmapImage(New Uri("Led rojo
apagado.png", UriKind.Relative)))
Recibidos = "" ' Limpiar.
Exit Select

Case "4=ON"
image_4.Source = (New BitmapImage(New Uri("Led rojo
encendido.png", UriKind.Relative)))
Recibidos = "" ' Limpiar.
Exit Select

Case "4=OFF"
image_4.Source = (New BitmapImage(New Uri("Led rojo
apagado.png", UriKind.Relative)))
Recibidos = "" ' Limpiar.
Exit Select
End Select
Next

End Sub

Private Sub Actualizar_estados()


Dim miBuffer As Byte() = Encoding.ASCII.GetBytes("ACTUALIZAR")
' Enva comando ACTUALIZAR por el puerto.
serialPort1.Write(miBuffer, 0, miBuffer.Length)
End Sub

Electrnica PIC | http://electronica-pic.blogspot.com.es 81


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Private Sub button_Actualizar_estados_Click(sender As Object, e As


RoutedEventArgs) Handles button_Actualizar_estados.Click
Actualizar_estados()
End Sub

Private Sub button_Limpiar_Click(sender As Object, e As RoutedEventArgs)


Handles button_Limpiar.Click
richTextBox.Document.Blocks.Clear() ' Limpiar contenido del richTextBox.
Recibidos = "" ' Limpiar variable.
End Sub

' Desde que cierres el programa, cierra el puerto.


Private Sub Form_Principal_Closing(sender As Object, e As
ComponentModel.CancelEventArgs) Handles Form_Principal.Closing
If serialPort1.IsOpen Then ' El puerto est abierto?
serialPort1.Close() ' Cerrar puerto.
End If
End Sub
End Class

Electrnica PIC | http://electronica-pic.blogspot.com.es 82


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Electrnica PIC | http://electronica-pic.blogspot.com.es 83


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Visual C++ CLR 2015

Electrnica PIC | http://electronica-pic.blogspot.com.es 84


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Antes de empezar, hay que instalar las herramientas comunes para Visual C++ 2015 como
indica la imagen.

Electrnica PIC | http://electronica-pic.blogspot.com.es 85


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Cuando tengas Visual Studio Community 2015 ya ejecutado, creamos un proyecto


nuevo.
ArchivoNuevoProyecto
Mirar imagen grande en la pgina siguiente.

Electrnica PIC | http://electronica-pic.blogspot.com.es 86


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Le ventana Nuevo proyecto est abierta y seguimos en orden lo que indica la imagen.
1) Visual C++ en Plantillas.
2) CLR.
3) Proyecto vaco de CLR.
4) Ponemos el nombre que queramos, en este caso lo he llamado
Entrada_Arduino_CPP_CLR_1.
5) Pulsamos Aceptar.

Electrnica PIC | http://electronica-pic.blogspot.com.es 87


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

En el Explorador de soluciones seleccionamos el nombre de nuestro proyecto, en este caso


Entrada_Arduino_CPP_CLR_1 como el primer paso.
En la barra de herramientas Proyecto, luego Agregar un nuevo elemento tal como indica en la
imagen de abajo.

Electrnica PIC | http://electronica-pic.blogspot.com.es 88


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Como muestra la imagen de abajo. Cloqueamos en Visual C++ UI y Sealamos Windows


Forms, le he aadido como nombre en el tercer paso Form_Principal, puedes poner cualquier
nombre, al final, pulsa Aceptar.

Electrnica PIC | http://electronica-pic.blogspot.com.es 89


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

En mi caso puede ver que hay un mensaje de error como muestra en esta imagen y en
la pgina siguiente.
No preocuparse, an no hemos acabado.

Electrnica PIC | http://electronica-pic.blogspot.com.es 90


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Cierra la pestaa pulsando la X. En la pgina siguiente lo volvers a abrir con el


formulario.

Electrnica PIC | http://electronica-pic.blogspot.com.es 91


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Indicamos en el Explorador de soluciones, hacemos clic en el botn derecho del


ratn y luego pulsamos Propiedades.

Electrnica PIC | http://electronica-pic.blogspot.com.es 92


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Sigue el procedimiento indicado abajo, en Subsistema tiene que ser Windows


(/SUBSYSTEM:WINDOWS), luego pulsas aplicar.

Electrnica PIC | http://electronica-pic.blogspot.com.es 93


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Vete a la pestaa Avanzadas, Punto de entrada escribes main.


Finalmente el botn Aceptar.

Electrnica PIC | http://electronica-pic.blogspot.com.es 94


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Escribe los cdigos necesarios como muestra en la imagen, pero antes, mira la
pgina siguiente que se ve ms grande y mejor.

Electrnica PIC | http://electronica-pic.blogspot.com.es 95


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Cambiamos las propiedades de cada componente o controles.

Panel:

Propiedad Cambie a
BorderStyle FixedSingle

Label:

Propiedad Cambie a
(Name) Label_Entrada
Text Leyendo...

PictureBox:

Propiedad Cambie a
(Name) pictureBox_Dibujo
SizeMode StretchImage
Electrnica PIC | http://electronica-pic.blogspot.com.es 96
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Seguimos en el componente PictureBox, pulsamos en la propiedad Image como indica abajo


para introducir dos imgenes de dos Led, encendido y apagado.

Electrnica PIC | http://electronica-pic.blogspot.com.es 97


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Buscamos y elegimos en este caso el Led rojo apagado.png.

Dejar claro que en la propiedad SizeMode del PicturreBox le he puesto StretchImage par
redimensionar el dibujo o imagen al cuadro.

En cuanto al formulario principal, en la propiedad StartPosition se ha cambiado a CenterScreen


para cuando lo compilemos o lo ejecutemos salga en el centro de la pantalla.

Electrnica PIC | http://electronica-pic.blogspot.com.es 98


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Aade el componente SerialPort haciendo doble clic en l o arrastrndolo al formulario.

Electrnica PIC | http://electronica-pic.blogspot.com.es 99


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Cambiamos las propiedades indicadas abajo.

SerialPort:

Tanto en Visual Studio como Arduino UNO y Arduino IDE tienen que funcionar en el mismo
puerto y baudios, en mi caso es:

Propiedad Cambie a
BuadRate 115200
PortName COM4
StopBits Two

En tu caso puede ser diferente, tanto el puerto y los baudios el que desee.

Electrnica PIC | http://electronica-pic.blogspot.com.es 100


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Tener claro estas lneas al recibir datos desde Arduino como ON y OFF.

Electrnica PIC | http://electronica-pic.blogspot.com.es 101


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 1:

Cdigo fuente del Ejemplo 1 de Visual C+ CLR.


#pragma once

namespace Entrada_Arduino_CPP_CLR_1 {

using namespace System;


using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

using namespace System::IO::Ports; // No olvidar.

/// <summary>
/// Resumen de Form_Principal
/// </summary>
public ref class Form_Principal : public System::Windows::Forms::Form
{
// Utilizaremos un string como buffer de recepcin.
String^ Recibidos;

public:
Form_Principal(void)
{
InitializeComponent();
//
//TODO: agregar cdigo de constructor aqu
//

if (!serialPort1->IsOpen)
{
try
{
serialPort1->Open();
}
catch (Exception ^ex)
{
MessageBox::Show(ex->ToString());
}

serialPort1->DataReceived += gcnew
SerialDataReceivedEventHandler(this, &Form_Principal::Recepcion);
}
}

// Al recibir datos.
private: Void Recepcion(Object^ sender,
SerialDataReceivedEventArgs^ e)
{
// Acumula los caracteres recibidos a nuestro 'buffer'
(string).
Recibidos += serialPort1->ReadExisting();

// Invocar o llamar al proceso de tramas.


Invoke(gcnew EventHandler(this,
&Form_Principal::Actualizar));
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 102


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

// Procesar los datos recibidos en el bufer y extraer tramas


completas.
private: Void Actualizar(Object^ sender, EventArgs^ e)
{
if (Recibidos == "ON")
{
panel1->BackColor = Color::Green;
label_Lectura->Text = "Activado";
pictureBox_Dibujo-
>Load("Led\\Led_rojo_encendido.png");
Recibidos = "";
}

else
{
panel1->BackColor = Color::Red;
label_Lectura->Text = "Desactivado";
pictureBox_Dibujo->Load("Led\\Led_rojo_apagado.png");
Recibidos = "";
}
}

protected:
/// <summary>
/// Limpiar los recursos que se estn usando.
/// </summary>
~Form_Principal()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Label^ label_titulo;
protected:
private: System::Windows::Forms::Panel^ panel1;
private: System::Windows::Forms::Label^ label_Lectura;
private: System::Windows::Forms::PictureBox^ pictureBox_Dibujo;
private: System::IO::Ports::SerialPort^ serialPort1;
private: System::Windows::Forms::Label^ label1;
private: System::ComponentModel::IContainer^ components;

private:
/// <summary>
/// Variable del diseador necesaria.
/// </summary>

#pragma region Windows Form Designer generated code


/// <summary>
/// Mtodo necesario para admitir el Diseador. No se puede
modificar
/// el contenido de este mtodo con el editor de cdigo.
/// </summary>
void InitializeComponent(void)
{
this->components = (gcnew
System::ComponentModel::Container());
System::ComponentModel::ComponentResourceManager^ resources
= (gcnew
System::ComponentModel::ComponentResourceManager(Form_Principal::typeid));
this->label_titulo = (gcnew System::Windows::Forms::Label());

Electrnica PIC | http://electronica-pic.blogspot.com.es 103


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

this->panel1 = (gcnew System::Windows::Forms::Panel());


this->label_Lectura = (gcnew
System::Windows::Forms::Label());
this->pictureBox_Dibujo = (gcnew
System::Windows::Forms::PictureBox());
this->serialPort1 = (gcnew
System::IO::Ports::SerialPort(this->components));
this->label1 = (gcnew System::Windows::Forms::Label());

(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox_Dibujo))->BeginInit();
this->SuspendLayout();
//
// label_titulo
//
this->label_titulo->AutoSize = true;
this->label_titulo->Font = (gcnew
System::Drawing::Font(L"Microsoft Sans Serif", 36,
System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->label_titulo->Location = System::Drawing::Point(29,
26);
this->label_titulo->Name = L"label_titulo";
this->label_titulo->Size = System::Drawing::Size(382, 55);
this->label_titulo->TabIndex = 0;
this->label_titulo->Text = L"Visual C++ CLR";
//
// panel1
//
this->panel1->BorderStyle =
System::Windows::Forms::BorderStyle::FixedSingle;
this->panel1->Location = System::Drawing::Point(23, 97);
this->panel1->Name = L"panel1";
this->panel1->Size = System::Drawing::Size(100, 100);
this->panel1->TabIndex = 1;
//
// label_Lectura
//
this->label_Lectura->AutoSize = true;
this->label_Lectura->Location = System::Drawing::Point(183,
138);
this->label_Lectura->Name = L"label_Lectura";
this->label_Lectura->Size = System::Drawing::Size(48, 13);
this->label_Lectura->TabIndex = 2;
this->label_Lectura->Text = L"Leyendo";
//
// pictureBox_Dibujo
//
this->pictureBox_Dibujo->Image =
(cli::safe_cast<System::Drawing::Image^>(resources-
>GetObject(L"pictureBox_Dibujo.Image")));
this->pictureBox_Dibujo->Location =
System::Drawing::Point(311, 97);
this->pictureBox_Dibujo->Name = L"pictureBox_Dibujo";
this->pictureBox_Dibujo->Size = System::Drawing::Size(100,
100);
this->pictureBox_Dibujo->SizeMode =
System::Windows::Forms::PictureBoxSizeMode::StretchImage;
this->pictureBox_Dibujo->TabIndex = 3;
this->pictureBox_Dibujo->TabStop = false;
//
// serialPort1

Electrnica PIC | http://electronica-pic.blogspot.com.es 104


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

//
this->serialPort1->BaudRate = 115200;
this->serialPort1->PortName = L"COM4";
this->serialPort1->StopBits =
System::IO::Ports::StopBits::Two;
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(349, 200);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(25, 13);
this->label1->TabIndex = 4;
this->label1->Text = L"Led";
//
// Form_Principal
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode =
System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(436, 262);
this->Controls->Add(this->label1);
this->Controls->Add(this->pictureBox_Dibujo);
this->Controls->Add(this->label_Lectura);
this->Controls->Add(this->panel1);
this->Controls->Add(this->label_titulo);
this->Name = L"Form_Principal";
this->StartPosition =
System::Windows::Forms::FormStartPosition::CenterScreen;
this->Text = L"Electrnica PIC - C++ 2015";
this->FormClosing += gcnew
System::Windows::Forms::FormClosingEventHandler(this,
&Form_Principal::Form_Principal_FormClosing);

(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox_Dibujo))->EndInit();
this->ResumeLayout(false);
this->PerformLayout();

}
#pragma endregion
private: System::Void Form_Principal_FormClosing(System::Object^ sender,
System::Windows::Forms::FormClosingEventArgs^ e) {
if (serialPort1->IsOpen) // El puerto est abierto?
{
serialPort1->Close(); // Puerto cerrado.
}
}
};
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 105


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 2:

Este ejemplo corresponde al cdigo del Ejemplo 2 de Arduino.

Si has llegado aqu directamente, se recomienda leer paso a paso el primer ejemplo.

Creamos el proyecto nuevo al igual que el Ejemplo 1 y esta vez lo llamamos


Entrada_Arduino_CPP_CLR_2, puedes poner el nombre que quieras del proyecto.

Electrnica PIC | http://electronica-pic.blogspot.com.es 106


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Cdigo fuente del Ejemplo 2 de Visual C++ CLR.


#pragma once

namespace Entrada_Arduino_CPP_CLR_2 {

using namespace System;


using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

using namespace System::IO::Ports; // No olvidar.


using namespace System::Text;

/// <summary>
/// Resumen de Form_Principal
/// </summary>
public ref class Form_Principal : public System::Windows::Forms::Form
{
public:

// Utilizaremos un string como buffer de recepcin.


String^ Recibidos;

Form_Principal(void)
{
InitializeComponent();

if (!serialPort1->IsOpen)
{
try
{
serialPort1->Open();
}
catch (Exception^ ex)
{
MessageBox::Show(ex->ToString());
}
serialPort1->DataReceived += gcnew
SerialDataReceivedEventHandler(this, &Form_Principal::Recepcion);
}
}

// Al recibir datos.
private: Void Recepcion(Object^ sender, SerialDataReceivedEventArgs^ e)
{
// Acumula los caracteres recibidos a nuestro 'buffer' (string).
Recibidos += serialPort1->ReadExisting();

// Invocar o llamar al proceso de tramas.


Invoke(gcnew EventHandler(this, &Form_Principal::Actualizar));
}

// Procesar los datos recibidos en el bufer y extraer tramas


completas.
private: Void Actualizar(Object^ sender, EventArgs^ e)
{
// Asignar el valor de la trama al richTextBox.
richTextBox1->Text += Recibidos;

Electrnica PIC | http://electronica-pic.blogspot.com.es 107


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

// Selecciona la posicin final para leer los mensajes entrantes.


richTextBox1->SelectionStart = richTextBox1->Text->Length;

// Mantiene el scroll en la entrada de cada mensaje.


richTextBox1->ScrollToCaret();
}

protected:
/// <summary>
/// Limpiar los recursos que se estn usando.
/// </summary>
~Form_Principal()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::RichTextBox^ richTextBox1;
protected:
private: System::Windows::Forms::Label^ label_Mensajes_desde_Arduino;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Button^ button_Actualizar;
private: System::Windows::Forms::Button^ button_Limpiar;
private: System::IO::Ports::SerialPort^ serialPort1;
private: System::ComponentModel::IContainer^ components;

private:
/// <summary>
/// Variable del diseador necesaria.
/// </summary>

#pragma region Windows Form Designer generated code


/// <summary>
/// Mtodo necesario para admitir el Diseador. No se puede
modificar
/// el contenido de este mtodo con el editor de cdigo.
/// </summary>
void InitializeComponent(void)
{
this->components = (gcnew
System::ComponentModel::Container());
this->richTextBox1 = (gcnew
System::Windows::Forms::RichTextBox());
this->label_Mensajes_desde_Arduino = (gcnew
System::Windows::Forms::Label());
this->label1 = (gcnew System::Windows::Forms::Label());
this->label2 = (gcnew System::Windows::Forms::Label());
this->button_Actualizar = (gcnew
System::Windows::Forms::Button());
this->button_Limpiar = (gcnew
System::Windows::Forms::Button());
this->serialPort1 = (gcnew
System::IO::Ports::SerialPort(this->components));
this->SuspendLayout();
//
// richTextBox1
//
this->richTextBox1->Location = System::Drawing::Point(12,
110);

Electrnica PIC | http://electronica-pic.blogspot.com.es 108


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

this->richTextBox1->Name = L"richTextBox1";
this->richTextBox1->Size = System::Drawing::Size(340, 140);
this->richTextBox1->TabIndex = 0;
this->richTextBox1->Text = L"";
//
// label_Mensajes_desde_Arduino
//
this->label_Mensajes_desde_Arduino->AutoSize = true;
this->label_Mensajes_desde_Arduino->Location =
System::Drawing::Point(12, 94);
this->label_Mensajes_desde_Arduino->Name =
L"label_Mensajes_desde_Arduino";
this->label_Mensajes_desde_Arduino->Size =
System::Drawing::Size(126, 13);
this->label_Mensajes_desde_Arduino->TabIndex = 1;
this->label_Mensajes_desde_Arduino->Text = L"Mensajes desde
Arduino:";
//
// label1
//
this->label1->AutoSize = true;
this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft
Sans Serif", 24, System::Drawing::FontStyle::Bold,
System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->label1->Location = System::Drawing::Point(52, 38);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(261, 37);
this->label1->TabIndex = 2;
this->label1->Text = L"Visual C++ CLR";
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(299, 9);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(53, 13);
this->label2->TabIndex = 3;
this->label2->Text = L"Ejemplo 2";
//
// button_Actualizar
//
this->button_Actualizar->Location =
System::Drawing::Point(196, 81);
this->button_Actualizar->Name = L"button_Actualizar";
this->button_Actualizar->Size = System::Drawing::Size(75,
23);
this->button_Actualizar->TabIndex = 4;
this->button_Actualizar->Text = L"Actualizar";
this->button_Actualizar->UseVisualStyleBackColor = true;
this->button_Actualizar->Click += gcnew
System::EventHandler(this, &Form_Principal::button_Actualizar_Click);
//
// button_Limpiar
//
this->button_Limpiar->Location = System::Drawing::Point(277,
81);
this->button_Limpiar->Name = L"button_Limpiar";
this->button_Limpiar->Size = System::Drawing::Size(75, 23);
this->button_Limpiar->TabIndex = 5;
this->button_Limpiar->Text = L"Limpiar";
this->button_Limpiar->UseVisualStyleBackColor = true;

Electrnica PIC | http://electronica-pic.blogspot.com.es 109


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

this->button_Limpiar->Click += gcnew
System::EventHandler(this, &Form_Principal::button_Limpiar_Click);
//
// serialPort1
//
this->serialPort1->BaudRate = 115200;
this->serialPort1->PortName = L"COM4";
this->serialPort1->StopBits =
System::IO::Ports::StopBits::Two;
//
// Form_Principal
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode =
System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(364, 262);
this->Controls->Add(this->button_Limpiar);
this->Controls->Add(this->button_Actualizar);
this->Controls->Add(this->label2);
this->Controls->Add(this->label1);
this->Controls->Add(this->label_Mensajes_desde_Arduino);
this->Controls->Add(this->richTextBox1);
this->Name = L"Form_Principal";
this->StartPosition =
System::Windows::Forms::FormStartPosition::CenterScreen;
this->Text = L"Electrnica PIC- C++ 2015";
this->FormClosing += gcnew
System::Windows::Forms::FormClosingEventHandler(this,
&Form_Principal::Form_Principal_FormClosing);
this->Load += gcnew System::EventHandler(this,
&Form_Principal::Form_Principal_Load);
this->ResumeLayout(false);
this->PerformLayout();

}
#pragma endregion

Void Actualizar()
{
array<Byte>^mBuffer = Encoding::ASCII-
>GetBytes("ACTUALIZAR"); // Enva comando ACTUALIZAR por el puerto.
serialPort1->Write(mBuffer, 0, mBuffer->Length);
}

private: System::Void button_Actualizar_Click(System::Object^ sender,


System::EventArgs^ e) {
Actualizar();
}
private: System::Void button_Limpiar_Click(System::Object^ sender,
System::EventArgs^ e) {
richTextBox1->Clear(); // Limpiar contenido del richTextBox.
Recibidos = "";
}
private: System::Void Form_Principal_FormClosing(System::Object^ sender,
System::Windows::Forms::FormClosingEventArgs^ e) {
if (serialPort1->IsOpen) // El puerto est abierto?
{
serialPort1->Close(); // Puerto cerrado.
}
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 110


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

private: System::Void Form_Principal_Load(System::Object^ sender,


System::EventArgs^ e) {
Actualizar();
}
};
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 111


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Ejemplo 3:

Este ejemplo corresponde al cdigo del Ejemplo 3 de Arduino.

Se trata en este caso unir los dos ejemplos de Visual Studio, las imgenes de los Leds y mostrar
mensajes en el richTextBox.

Se recomienda mirar el primer ejemplo para seguir bien la gua o entender el concepto si eres
muy novel.

Electrnica PIC | http://electronica-pic.blogspot.com.es 112


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Cdigo fuente del Ejemplo 3 de Visual C++ CLR.


#pragma once

namespace Entrada_Arduino_CPP_CLR_3 {

using namespace System;


using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

using namespace System::IO::Ports; // No olvidar.


using namespace System::Text;

/// <summary>
/// Resumen de Form_Principal
/// </summary>
public ref class Form_Principal : public Form
{
public:

// Utilizaremos un string como buffer de recepcin.


String^ Recibidos;

Form_Principal(void)
{
InitializeComponent();

if (!serialPort1->IsOpen)
{
try
{
serialPort1->Open();
}
catch (Exception^ ex)
{
MessageBox::Show(ex->ToString());
}
serialPort1->DataReceived += gcnew
SerialDataReceivedEventHandler(this, &Form_Principal::Recepcion);

}
}

// Al recibir datos.
private: Void Recepcion(Object^ sender,
SerialDataReceivedEventArgs^ e)
{
// Acumula los caracteres recibidos a nuestro 'buffer'
(string).
Recibidos += serialPort1->ReadExisting();

// Invocar o llamar al proceso de tramas.


Invoke(gcnew EventHandler(this,
&Form_Principal::Actualizar));
}

// Procesar los datos recibidos en el bufer y extraer tramas


completas.
private: Void Actualizar(Object^ sender, EventArgs^ e)

Electrnica PIC | http://electronica-pic.blogspot.com.es 113


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

{
// Asignar el valor de la trama al richTextBox.
richTextBox1->Text += Recibidos;

// Selecciona la posicin final para leer los mensajes entrantes.


richTextBox1->SelectionStart = richTextBox1->Text->Length;

// Mantiene el scroll en la entrada de cada mensaje.


richTextBox1->ScrollToCaret();

array<wchar_t, 1>^ Delimitador = { ' ','\r','\n' };

array<String^>^ Palabras = Recibidos->Split(Delimitador);

for each (String^ Comandos in Palabras)


{
if (Comandos == "1=ON")
pictureBox1->Load("Led\\Led_rojo_encendido.png");
else if (Comandos == "1=OFF")
pictureBox1->Load("Led\\Led_rojo_apagado.png");
else if (Comandos == "2=ON")
pictureBox2->Load("Led\\Led_rojo_encendido.png");
else if (Comandos == "2=OFF")
pictureBox2->Load("Led\\Led_rojo_apagado.png");
else if (Comandos == "3=ON")
pictureBox3->Load("Led\\Led_rojo_encendido.png");
else if (Comandos == "3=OFF")
pictureBox3->Load("Led\\Led_rojo_apagado.png");
else if (Comandos == "4=ON")
pictureBox4->Load("Led\\Led_rojo_encendido.png");
else if (Comandos == "4=OFF")
pictureBox4->Load("Led\\Led_rojo_apagado.png");

Recibidos = "";

}
richTextBox1->Text += " " + DateTime::Now.ToString() + "\r";
}

//
#################################################################################
###############################

protected:
/// <summary>
/// Limpiar los recursos que se estn usando.
/// </summary>
~Form_Principal()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Label^ label_Visual_Cpp_CLR;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::PictureBox^ pictureBox1;
private: System::Windows::Forms::PictureBox^ pictureBox2;
private: System::Windows::Forms::PictureBox^ pictureBox3;
private: System::Windows::Forms::PictureBox^ pictureBox4;
private: System::Windows::Forms::Label^ label_Led_1;

Electrnica PIC | http://electronica-pic.blogspot.com.es 114


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

private: System::Windows::Forms::Label^ label2;


private: System::Windows::Forms::Label^ label3;
private: System::Windows::Forms::Label^ label4;
private: System::Windows::Forms::RichTextBox^ richTextBox1;
private: System::Windows::Forms::Button^ button_Limpiar;
private: System::Windows::Forms::Button^ button_Actualizar;
private: System::Windows::Forms::Label^ label_Mensajes_desde_Arduino;
private: System::IO::Ports::SerialPort^ serialPort1;
private: System::ComponentModel::IContainer^ components;
protected:

private:
/// <summary>
/// Variable del diseador necesaria.
/// </summary>

#pragma region Windows Form Designer generated code


/// <summary>
/// Mtodo necesario para admitir el Diseador. No se puede
modificar
/// el contenido de este mtodo con el editor de cdigo.
/// </summary>
void InitializeComponent(void)
{
this->components = (gcnew
System::ComponentModel::Container());
System::ComponentModel::ComponentResourceManager^ resources
= (gcnew
System::ComponentModel::ComponentResourceManager(Form_Principal::typeid));
this->label_Visual_Cpp_CLR = (gcnew
System::Windows::Forms::Label());
this->label1 = (gcnew System::Windows::Forms::Label());
this->pictureBox1 = (gcnew
System::Windows::Forms::PictureBox());
this->pictureBox2 = (gcnew
System::Windows::Forms::PictureBox());
this->pictureBox3 = (gcnew
System::Windows::Forms::PictureBox());
this->pictureBox4 = (gcnew
System::Windows::Forms::PictureBox());
this->label_Led_1 = (gcnew System::Windows::Forms::Label());
this->label2 = (gcnew System::Windows::Forms::Label());
this->label3 = (gcnew System::Windows::Forms::Label());
this->label4 = (gcnew System::Windows::Forms::Label());
this->richTextBox1 = (gcnew
System::Windows::Forms::RichTextBox());
this->button_Limpiar = (gcnew
System::Windows::Forms::Button());
this->button_Actualizar = (gcnew
System::Windows::Forms::Button());
this->label_Mensajes_desde_Arduino = (gcnew
System::Windows::Forms::Label());
this->serialPort1 = (gcnew
System::IO::Ports::SerialPort(this->components));

(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox1))->BeginInit();

(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox2))->BeginInit();

Electrnica PIC | http://electronica-pic.blogspot.com.es 115


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox3))->BeginInit();

(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox4))->BeginInit();
this->SuspendLayout();
//
// label_Visual_Cpp_CLR
//
this->label_Visual_Cpp_CLR->AutoSize = true;
this->label_Visual_Cpp_CLR->Font = (gcnew
System::Drawing::Font(L"Microsoft Sans Serif", 24,
System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->label_Visual_Cpp_CLR->Location =
System::Drawing::Point(79, 9);
this->label_Visual_Cpp_CLR->Name = L"label_Visual_Cpp_CLR";
this->label_Visual_Cpp_CLR->Size = System::Drawing::Size(261,
37);
this->label_Visual_Cpp_CLR->TabIndex = 0;
this->label_Visual_Cpp_CLR->Text = L"Visual C++ CLR";
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(378, 9);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(53, 13);
this->label1->TabIndex = 1;
this->label1->Text = L"Ejemplo 3";
//
// pictureBox1
//
this->pictureBox1->Image =
(cli::safe_cast<System::Drawing::Image^>(resources-
>GetObject(L"pictureBox1.Image")));
this->pictureBox1->Location = System::Drawing::Point(13, 73);
this->pictureBox1->Name = L"pictureBox1";
this->pictureBox1->Size = System::Drawing::Size(100, 100);
this->pictureBox1->SizeMode =
System::Windows::Forms::PictureBoxSizeMode::StretchImage;
this->pictureBox1->TabIndex = 2;
this->pictureBox1->TabStop = false;
//
// pictureBox2
//
this->pictureBox2->Image =
(cli::safe_cast<System::Drawing::Image^>(resources-
>GetObject(L"pictureBox2.Image")));
this->pictureBox2->Location = System::Drawing::Point(119,
73);
this->pictureBox2->Name = L"pictureBox2";
this->pictureBox2->Size = System::Drawing::Size(100, 100);
this->pictureBox2->SizeMode =
System::Windows::Forms::PictureBoxSizeMode::StretchImage;
this->pictureBox2->TabIndex = 3;
this->pictureBox2->TabStop = false;
//
// pictureBox3
//

Electrnica PIC | http://electronica-pic.blogspot.com.es 116


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

this->pictureBox3->Image =
(cli::safe_cast<System::Drawing::Image^>(resources-
>GetObject(L"pictureBox3.Image")));
this->pictureBox3->Location = System::Drawing::Point(225,
73);
this->pictureBox3->Name = L"pictureBox3";
this->pictureBox3->Size = System::Drawing::Size(100, 100);
this->pictureBox3->SizeMode =
System::Windows::Forms::PictureBoxSizeMode::StretchImage;
this->pictureBox3->TabIndex = 4;
this->pictureBox3->TabStop = false;
//
// pictureBox4
//
this->pictureBox4->Image =
(cli::safe_cast<System::Drawing::Image^>(resources-
>GetObject(L"pictureBox4.Image")));
this->pictureBox4->Location = System::Drawing::Point(331,
73);
this->pictureBox4->Name = L"pictureBox4";
this->pictureBox4->Size = System::Drawing::Size(100, 100);
this->pictureBox4->SizeMode =
System::Windows::Forms::PictureBoxSizeMode::StretchImage;
this->pictureBox4->TabIndex = 5;
this->pictureBox4->TabStop = false;
//
// label_Led_1
//
this->label_Led_1->AutoSize = true;
this->label_Led_1->Location = System::Drawing::Point(45, 57);
this->label_Led_1->Name = L"label_Led_1";
this->label_Led_1->Size = System::Drawing::Size(34, 13);
this->label_Led_1->TabIndex = 6;
this->label_Led_1->Text = L"Led 1";
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(151, 57);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(34, 13);
this->label2->TabIndex = 7;
this->label2->Text = L"Led 2";
//
// label3
//
this->label3->AutoSize = true;
this->label3->Location = System::Drawing::Point(256, 56);
this->label3->Name = L"label3";
this->label3->Size = System::Drawing::Size(34, 13);
this->label3->TabIndex = 8;
this->label3->Text = L"Led 3";
//
// label4
//
this->label4->AutoSize = true;
this->label4->Location = System::Drawing::Point(363, 57);
this->label4->Name = L"label4";
this->label4->Size = System::Drawing::Size(34, 13);
this->label4->TabIndex = 9;
this->label4->Text = L"Led 4";
//

Electrnica PIC | http://electronica-pic.blogspot.com.es 117


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

// richTextBox1
//
this->richTextBox1->Location = System::Drawing::Point(12,
221);
this->richTextBox1->Name = L"richTextBox1";
this->richTextBox1->Size = System::Drawing::Size(419, 114);
this->richTextBox1->TabIndex = 10;
this->richTextBox1->Text = L"";
//
// button_Limpiar
//
this->button_Limpiar->Location = System::Drawing::Point(356,
192);
this->button_Limpiar->Name = L"button_Limpiar";
this->button_Limpiar->Size = System::Drawing::Size(75, 23);
this->button_Limpiar->TabIndex = 11;
this->button_Limpiar->Text = L"Limpiar";
this->button_Limpiar->UseVisualStyleBackColor = true;
this->button_Limpiar->Click += gcnew
System::EventHandler(this, &Form_Principal::button_Limpiar_Click);
//
// button_Actualizar
//
this->button_Actualizar->Location =
System::Drawing::Point(275, 192);
this->button_Actualizar->Name = L"button_Actualizar";
this->button_Actualizar->Size = System::Drawing::Size(75,
23);
this->button_Actualizar->TabIndex = 12;
this->button_Actualizar->Text = L"Actualizar";
this->button_Actualizar->UseVisualStyleBackColor = true;
this->button_Actualizar->Click += gcnew
System::EventHandler(this, &Form_Principal::button_Actualizar_Click);
//
// label_Mensajes_desde_Arduino
//
this->label_Mensajes_desde_Arduino->AutoSize = true;
this->label_Mensajes_desde_Arduino->Location =
System::Drawing::Point(12, 202);
this->label_Mensajes_desde_Arduino->Name =
L"label_Mensajes_desde_Arduino";
this->label_Mensajes_desde_Arduino->Size =
System::Drawing::Size(126, 13);
this->label_Mensajes_desde_Arduino->TabIndex = 13;
this->label_Mensajes_desde_Arduino->Text = L"Mensajes desde
Arduino:";
//
// serialPort1
//
this->serialPort1->BaudRate = 115200;
this->serialPort1->PortName = L"COM4";
this->serialPort1->StopBits =
System::IO::Ports::StopBits::Two;
//
// Form_Principal
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode =
System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(443, 347);
this->Controls->Add(this->label_Mensajes_desde_Arduino);
this->Controls->Add(this->button_Actualizar);

Electrnica PIC | http://electronica-pic.blogspot.com.es 118


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

this->Controls->Add(this->button_Limpiar);
this->Controls->Add(this->richTextBox1);
this->Controls->Add(this->label4);
this->Controls->Add(this->label3);
this->Controls->Add(this->label2);
this->Controls->Add(this->label_Led_1);
this->Controls->Add(this->pictureBox4);
this->Controls->Add(this->pictureBox3);
this->Controls->Add(this->pictureBox2);
this->Controls->Add(this->pictureBox1);
this->Controls->Add(this->label1);
this->Controls->Add(this->label_Visual_Cpp_CLR);
this->Name = L"Form_Principal";
this->StartPosition =
System::Windows::Forms::FormStartPosition::CenterScreen;
this->Text = L"Electrnica PIC - C++ CLR";
this->FormClosing += gcnew
System::Windows::Forms::FormClosingEventHandler(this,
&Form_Principal::Form_Principal_FormClosing);
this->Load += gcnew System::EventHandler(this,
&Form_Principal::Form_Principal_Load);

(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox1))->EndInit();

(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox2))->EndInit();

(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox3))->EndInit();

(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox4))->EndInit();
this->ResumeLayout(false);
this->PerformLayout();

}
#pragma endregion

Void Actualizar()
{
array<Byte>^mBuffer = Encoding::ASCII-
>GetBytes("ACTUALIZAR"); // Enva comando ACTUALIZAR por el puerto.
serialPort1->Write(mBuffer, 0, mBuffer->Length);
}

private: System::Void button_Actualizar_Click(System::Object^


sender, System::EventArgs^ e) {
Actualizar();
}

private: System::Void button_Limpiar_Click(System::Object^ sender,


System::EventArgs^ e) {
richTextBox1->Clear(); // Limpiar contenido del richTextBox.
Recibidos = "";
}
private: System::Void Form_Principal_FormClosing(System::Object^ sender,
System::Windows::Forms::FormClosingEventArgs^ e) {
if (serialPort1->IsOpen) // El puerto est abierto?
{
serialPort1->Close(); // Puerto cerrado.
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 119


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

}
private: System::Void Form_Principal_Load(System::Object^ sender,
System::EventArgs^ e) {
Actualizar();
}
};
}

Electrnica PIC | http://electronica-pic.blogspot.com.es 120


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Vdeos

Una muestra de un vdeo en este caso con Visual C# 2015 que enciende y apaga un Led. Vale
para los dems lenguajes.

Ttulo:

Encender y Apagar un Led Con Arduino y Visual Studio 2015 / Turn on and off an LED with
Arduino

Enlace:

https://www.youtube.com/watch?v=F6P0ZOceTko

Electrnica PIC | http://electronica-pic.blogspot.com.es 121


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Enlace:

https://www.youtube.com/watch?v=YJ4bjwFSH6o

Electrnica PIC | http://electronica-pic.blogspot.com.es 122


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Enlaces
Descarga ejemplos de este tutorial:

Enlace 1.

Enlace 2.

Arduino:
https://www.arduino.cc/

Foro en espaol de Arduino:


http://forum.arduino.cc/index.php?board=32.0

Visual Studio 2015 Community.

https://www.visualstudio.com/es-es/products/visual-studio-community-vs.aspx

Visual Studio 2015 Express

https://www.visualstudio.com/es-es/products/visual-studio-express-vs.aspx

Foro MSDN:

https://social.msdn.microsoft.com/Forums/es-es/home

Foro TechNET:

https://social.technet.microsoft.com/Forums/es-es/home

Electrnica PIC | http://electronica-pic.blogspot.com.es 123


LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015

Autor

Electrnica PIC
http://electronica-pic.blogspot.com.es

Autor: ngel Acaymo M. G.


Versin: 1.00
Publicado: 21-02-2016
Contacto: metaconta@gmail.com
Comentarios: http://electronica-pic.blogspot.com.es/2015/12/entrada-digital-con-arduino-y-
visual.html

Parte de este tutorial es gracias al equipo del foro en espaol


de Arduino.

Electrnica PIC | http://electronica-pic.blogspot.com.es 124

Вам также может понравиться