SlideShare ist ein Scribd-Unternehmen logo
1 von 125
Downloaden Sie, um offline zu lesen
Ángel Acaymo M. G.
Electrónica PIC
http://electronica-pic.blogspot.com.es
Lectura de entradas digitales con
Arduino y Visual Studio 2015
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 1
Índice
¿Qué puerto uso? ………………………………………………………………………………………………..…………. 3.
Códigos 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.
Vídeos …………………………………………………………………………………………………………………………..… 121.
Enlaces ………………………………………………………………………………………………………………………….. 123.
Autor ……………………………………………………………………………………………………………………..……….. 124.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 2
En esta ocasión 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 tecnologías disponibles como Visual C#, Visual C++, Visual Basic .net, WPF C# y
WPF VB. No olvidar que también les vale Visual Studio Express 2015, en general es la versión
más capada, lo que necesitamos en este momento lo incluye sin problemas.
Hay dos códigos 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 más
encender Arduino o Resetearlo, a parte que muestra la información 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 códigos fuentes de ejemplos de Visual Studio, Arduino e imágenes de los Led:
Enlace
Enlace
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 3
¿Qué puerto uso?
Para saber que puerto estamos usando con Arduino.
Entras desde Windows “InicioPanel de controlTodos los elementos de Panel de
controlSistema”.
Luego pulsas “Administrador de dispositivos”.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 4
En mi caso usaré el COM4, en tu caso puede ser diferente, así que para todo usarás el que te
haya tocado.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 5
Haz doble clic en Arduino UNO (COM4) para mostrar la ventana Propiedades: Arduino UNO
(COM4). En este caso para todo usaré la configuración que obtienes en la imagen, tanto para
Arduino UNO, en el Monitor Serie, en tu interfaz hecho con Visual Studio y en el código de
Arduino.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 6
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 7
Códigos 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 botón 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 número 8.
// Si el pulsador está pulsado, se enciende el Led 13 y
// envía comando HIGH por el puerto serie.
if(estadoBoton != anteriorBoton) // Comprueba si ha habido un cambio en el estado del
botón.
{
flagMensaje = 0; // Resetea la bandera a 0.
anteriorBoton = estadoBoton; // Guarda el estado actual del botón.
}
if (estadoBoton == HIGH && flagMensaje == 0) // Comprueba que el botón 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
próxima vez.
flagMensaje++;
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 8
// De lo contrario, Led 13 apagado y envía LOW al puerto serie.
else if(flagMensaje == 0) // Si el botón no está presionado y aún no se envía 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
próxima vez.
flagMensaje++;
}
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 9
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 físicamente Arduino UNO, también muestra los
últimos interruptores que tienes activados o no en ese momento. Si ejecutas a aplicación, de
entrada no muestra nada, pulsas el botón “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);
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 10
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");
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 11
Serial.println(buffer);
estadoBotonAnt1 = estadoBoton1;
estadoBotonAnt2 = estadoBoton2;
estadoBotonAnt3 = estadoBoton3;
estadoBotonAnt4 = estadoBoton4;
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 12
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);
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 13
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;
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 14
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 15
Visual C# AWF 2015
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 16
Ejemplo 1:
Este ejemplo corresponde al código del Ejemplo 1 de Arduino.
Creamos un proyecto nuevo con Visual C#.
Selecciona Entorno clásico en Visual C#, Aplicación de Windows Forms, he puesto como
nombre del proyecto en este caso Entrada_Arduino_AWF_1_CS, luego pulsar Aceptar.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 17
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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 18
Seguimos en el componente PictureBox, pulsamos … en la propiedad Image como indica abajo
para introducir dos imágenes de dos Led, encendido y apagado.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 19
Se abre un cuadro llamado Seleccionar recurso en el cual podemos añadir las imágenes que
queramos.
Pulsamos el botón Importar… y elegimos las imágenes de Leds que queramos, en este caso
selecciono el rojo apagado y encendido.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 20
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.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 21
Añade el componente SerialPort haciendo doble clic en él o arrastrándolo al formulario.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 22
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.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 23
Tener claro estas líneas al recibir datos desde Arduino como ON y OFF.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 24
Ejemplo 1:
Código 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 recepción.
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));
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 25
// 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 aplicación.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) // ¿El puerto está abierto?
{
serialPort1.Close(); // Cerrar puerto.
}
}
}
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 26
Ejemplo 2:
Este ejemplo corresponde al código 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.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 27
Código 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 recepción.
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));
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 28
// 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 posición 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"); // Envía
comando ACTUALIZAR por el puerto.
serialPort1.Write(mBuffer, 0, mBuffer.Length);
}
private void Form1_Load(object sender, EventArgs e)
{
Actualizar();
}
}
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 29
Ejemplo 3:
Este ejemplo corresponde al código del Ejemplo 3 de Arduino.
Se trata en este caso unir los dos ejemplos de Visual Studio, las imágenes de los Leds y mostrar
mensajes en el richTextBox.
Se recomienda mirar el primer ejemplo para seguir bien la guía o entender el concepto si eres
muy novel.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 30
Código 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 recepción.
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 posición final para leer los mensajes entrantes.
richTextBox1.SelectionStart = richTextBox1.Text.Length;
// Mantiene el scroll en la entrada de cada mensaje.
richTextBox1.ScrollToCaret();
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 31
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";
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 32
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"); // Envía
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 = "";
}
}
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 33
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 34
Visual C# WPF 2015
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 35
Creamos un proyecto nuevo con Visual C#.
Como nombre en este caso lo he llamado Entrada_Arduino_WPF_1_CS.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 36
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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 37
Seguimos en el componente image, pulsamos … en la propiedad Image como indica abajo,
Proyecto  Agregar elemento existente…
Podemos seleccionar las imágenes que queremos, en este caso he elegido el Led apagado y el
otro encendido de color rojo. Para finalizar, pulsa el botón Agregar.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 38
En la propiedad Source, eliges el Led rojo apagado, si lo deseas, puede escoger el verde, pero
que sea apagado.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 39
Tener claro estas líneas al recibir datos desde Arduino como ON y OFF.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 40
Ejemplo 1:
Código 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>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
// Utilizaremos un string como buffer de recepción.
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
aplicación.
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 41
// Ejecutar la función Recepción 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.
}
}
}
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 42
Este ejemplo corresponde al código 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.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 43
Ejemplo 2:
Código 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>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
// Utilizaremos un string como buffer de recepción.
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
aplicación.
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 44
// Ejecutar la función Recepción 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"); // Envía
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.
}
}
}
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 45
Ejemplo 3:
Este ejemplo corresponde al código del Ejemplo 3 de Arduino.
Se trata en este caso unir los dos ejemplos de Visual Studio, las imágenes de los Leds y mostrar
mensajes en el richTextBox.
Se recomienda mirar el primer ejemplo para seguir bien la guía o entender el concepto si eres
muy novel.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 46
Ejemplo 3:
Código 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>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
// Utilizaremos un string como buffer de recepción.
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
aplicación.
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 47
// Ejecutar la función Recepción 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;
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 48
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"); // Envía
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.
}
}
}
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 49
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 50
Visual Basic AWF 2015
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 51
Ejemplo 1:
Este ejemplo corresponde al código del Ejemplo 1 de Arduino.
Creamos un proyecto nuevo con Visual Basic.
Selecciona Entorno clásico en Visual Basic, Aplicación de Windows Forms, he puesto como
nombre del proyecto en este caso Entrada_Arduino_AWF_1_VB, luego pulsar Aceptar.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 52
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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 53
Seguimos en el componente PictureBox, pulsamos … en la propiedad Image como indica abajo
para introducir dos imágenes de dos Led, encendido y apagado.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 54
Se abre un cuadro llamado Seleccionar recurso en el cual podemos añadir las imágenes que
queramos.
Pulsamos el botón Importar… y elegimos las imágenes de Leds que queramos, en este caso
selecciono el rojo apagado y encendido.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 55
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.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 56
Añade el componente SerialPort haciendo doble clic en él o arrastrándolo al formulario.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 57
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.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 58
Tener claro estas líneas al recibir datos desde Arduino como ON y OFF.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 59
Ejemplo 1:
Código 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 recepción.
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 función 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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 60
Ejemplo 2:
Este ejemplo corresponde al código 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.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 61
Imports System.IO.Ports ' No olvidar.
Imports System.Text
Imports System.Threading
Public Class Form1
' Utilizaremos un string como buffer de recepción.
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 función 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 posición 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")
' Envía 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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 62
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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 63
Ejemplo 3:
Este ejemplo corresponde al código del Ejemplo 3 de Arduino.
Se trata en este caso unir los dos ejemplos de Visual Studio, las imágenes de los Leds y mostrar
mensajes en el richTextBox.
Se recomienda mirar el primer ejemplo para seguir bien la guía o entender el concepto si eres
muy novel.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 64
Imports System.IO.Ports ' No olvidar.
Imports System.Text
Imports System.Threading
Public Class Form1
' Utilizaremos un string como buffer de recepción.
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 función 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 posición 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)
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 65
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") ' Envía
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.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 66
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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 67
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 68
Visual Basic WPF 2015
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 69
Creamos un proyecto nuevo con Visual Basic.
Como nombre en este caso lo he llamado Entrada_Arduino_WPF_1_VB.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 70
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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 71
Seguimos en el componente image, pulsamos … en la propiedad Image como indica abajo,
Proyecto  Agregar elemento existente…
Podemos seleccionar las imágenes que queremos, en este caso he elegido el Led apagado y el
otro encendido de color rojo. Para finalizar, pulsa el botón Agregar.
En la propiedad Source, eliges el Led rojo apagado, si lo deseas, puede escoger el verde, pero
que sea apagado.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 72
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 73
Tener claro estas líneas al recibir datos desde Arduino como ON y OFF.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 74
Ejemplo 1:
Código 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 recepción.
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 aplicación.
If Not serialPort1.IsOpen Then
Try
serialPort1.Open()
Catch ex As System.Exception
MessageBox.Show(ex.ToString())
End Try
End If
' Ejecutar la función Recepción 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)))
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 75
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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 76
Este ejemplo corresponde al código 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.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 77
Ejemplo 2:
Código 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 recepción.
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 aplicación.
If Not serialPort1.IsOpen Then
Try
serialPort1.Open()
Catch ex As System.Exception
MessageBox.Show(ex.ToString())
End Try
End If
' Ejecutar la función Recepción 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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 78
Private Sub Actualizar_estados()
Dim miBuffer As Byte() = Encoding.ASCII.GetBytes("ACTUALIZAR")
' Envía 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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 79
Ejemplo 3:
Este ejemplo corresponde al código del Ejemplo 3 de Arduino.
Se trata en este caso unir los dos ejemplos de Visual Studio, las imágenes de los Leds y mostrar
mensajes en el richTextBox.
Se recomienda mirar el primer ejemplo para seguir bien la guía o entender el concepto si eres
muy novel.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 80
Ejemplo 3:
Código 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 recepción.
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 aplicación.
If Not serialPort1.IsOpen Then
Try
serialPort1.Open()
Catch ex As System.Exception
MessageBox.Show(ex.ToString())
End Try
End If
' Ejecutar la función Recepción 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}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 81
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")
' Envía comando ACTUALIZAR por el puerto.
serialPort1.Write(miBuffer, 0, miBuffer.Length)
End Sub
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 82
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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 83
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 84
Visual C++ CLR 2015
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 85
Antes de empezar, hay que instalar las herramientas comunes para Visual C++ 2015 como
indica la imagen.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 86
Cuando tengas Visual Studio Community 2015 ya ejecutado, creamos un proyecto
nuevo.
ArchivoNuevoProyecto…
Mirar imagen grande en la página siguiente.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 87
Le ventana Nuevo proyecto está abierta y seguimos en orden lo que indica la imagen.
1) Visual C++ en Plantillas.
2) CLR.
3) Proyecto vacío de CLR.
4) Ponemos el nombre que queramos, en este caso lo he llamado
Entrada_Arduino_CPP_CLR_1.
5) Pulsamos Aceptar.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 88
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.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 89
Como muestra la imagen de abajo. Cloqueamos en Visual C++ UI y Señalamos Windows
Forms, le he añadido como nombre en el tercer paso Form_Principal, puedes poner cualquier
nombre, al final, pulsa Aceptar.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 90
En mi caso puede ver que hay un mensaje de error como muestra en esta imagen y en
la página siguiente.
No preocuparse, aún no hemos acabado.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 91
Cierra la pestaña pulsando la X. En la página siguiente lo volverás a abrir con el
formulario.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 92
Indicamos en el “Explorador de soluciones”, hacemos clic en el botón derecho del
ratón y luego pulsamos “Propiedades”.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 93
Sigue el procedimiento indicado abajo, en Subsistema tiene que ser Windows
(/SUBSYSTEM:WINDOWS), luego pulsas aplicar.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 94
Vete a la pestaña “Avanzadas”, Punto de entrada escribes main.
Finalmente el botón Aceptar.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 95
Escribe los códigos necesarios como muestra en la imagen, pero antes, mira la
página siguiente que se ve más grande y mejor.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 96
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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 97
Seguimos en el componente PictureBox, pulsamos … en la propiedad Image como indica abajo
para introducir dos imágenes de dos Led, encendido y apagado.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 98
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.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 99
Añade el componente SerialPort haciendo doble clic en él o arrastrándolo al formulario.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 100
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.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 101
Tener claro estas líneas al recibir datos desde Arduino como ON y OFF.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 102
Ejemplo 1:
Código 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 recepción.
String^ Recibidos;
public:
Form_Principal(void)
{
InitializeComponent();
//
//TODO: agregar código 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));
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 103
// 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("LedLed_rojo_encendido.png");
Recibidos = "";
}
else
{
panel1->BackColor = Color::Red;
label_Lectura->Text = "Desactivado";
pictureBox_Dibujo->Load("LedLed_rojo_apagado.png");
Recibidos = "";
}
}
protected:
/// <summary>
/// Limpiar los recursos que se estén 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 diseñador necesaria.
/// </summary>
#pragma region Windows Form Designer generated code
/// <summary>
/// Método necesario para admitir el Diseñador. No se puede
modificar
/// el contenido de este método con el editor de código.
/// </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());
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 104
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
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 105
//
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"Electrónica 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.
}
}
};
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 106
Ejemplo 2:
Este ejemplo corresponde al código 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.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 107
Código 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 recepción.
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;
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 108
// Selecciona la posición 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 estén 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 diseñador necesaria.
/// </summary>
#pragma region Windows Form Designer generated code
/// <summary>
/// Método necesario para admitir el Diseñador. No se puede
modificar
/// el contenido de este método con el editor de código.
/// </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);
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 109
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;
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 110
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"Electrónica 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"); // Envía 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.
}
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 111
private: System::Void Form_Principal_Load(System::Object^ sender,
System::EventArgs^ e) {
Actualizar();
}
};
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 112
Ejemplo 3:
Este ejemplo corresponde al código del Ejemplo 3 de Arduino.
Se trata en este caso unir los dos ejemplos de Visual Studio, las imágenes de los Leds y mostrar
mensajes en el richTextBox.
Se recomienda mirar el primer ejemplo para seguir bien la guía o entender el concepto si eres
muy novel.
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 113
Código 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 recepción.
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)
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 114
{
// Asignar el valor de la trama al richTextBox.
richTextBox1->Text += Recibidos;
// Selecciona la posición 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("LedLed_rojo_encendido.png");
else if (Comandos == "1=OFF")
pictureBox1->Load("LedLed_rojo_apagado.png");
else if (Comandos == "2=ON")
pictureBox2->Load("LedLed_rojo_encendido.png");
else if (Comandos == "2=OFF")
pictureBox2->Load("LedLed_rojo_apagado.png");
else if (Comandos == "3=ON")
pictureBox3->Load("LedLed_rojo_encendido.png");
else if (Comandos == "3=OFF")
pictureBox3->Load("LedLed_rojo_apagado.png");
else if (Comandos == "4=ON")
pictureBox4->Load("LedLed_rojo_encendido.png");
else if (Comandos == "4=OFF")
pictureBox4->Load("LedLed_rojo_apagado.png");
Recibidos = "";
}
richTextBox1->Text += " " + DateTime::Now.ToString() + "r";
}
//
#################################################################################
###############################
protected:
/// <summary>
/// Limpiar los recursos que se estén 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;
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 115
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 diseñador necesaria.
/// </summary>
#pragma region Windows Form Designer generated code
/// <summary>
/// Método necesario para admitir el Diseñador. No se puede
modificar
/// el contenido de este método con el editor de código.
/// </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();
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 116
(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
//
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 117
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";
//
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 118
// 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);
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 119
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"Electrónica 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"); // Envía 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.
}
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Electrónica PIC | http://electronica-pic.blogspot.com.es 120
}
private: System::Void Form_Principal_Load(System::Object^ sender,
System::EventArgs^ e) {
Actualizar();
}
};
}
Entrada digital con arduino y visual studio 2015
Entrada digital con arduino y visual studio 2015
Entrada digital con arduino y visual studio 2015
Entrada digital con arduino y visual studio 2015

Weitere ähnliche Inhalte

Was ist angesagt?

Tutorial básico control puerto paralelo con visual basic 6.0
Tutorial básico control puerto paralelo con visual basic 6.0Tutorial básico control puerto paralelo con visual basic 6.0
Tutorial básico control puerto paralelo con visual basic 6.0
Eddy Solano
 
1.2.4.5 packet tracer network representation - ilm
1.2.4.5 packet tracer   network representation - ilm1.2.4.5 packet tracer   network representation - ilm
1.2.4.5 packet tracer network representation - ilm
mariosaavedra27
 
Compuertas logicas
Compuertas logicasCompuertas logicas
Compuertas logicas
Moises
 
Arduino: Display de 7 segmentos y como crear un dado electrónico
Arduino: Display de 7 segmentos y como crear un dado electrónicoArduino: Display de 7 segmentos y como crear un dado electrónico
Arduino: Display de 7 segmentos y como crear un dado electrónico
SANTIAGO PABLO ALBERTO
 
Conversion plc-5-o-slc-500-a-logix-5000-esp
Conversion plc-5-o-slc-500-a-logix-5000-espConversion plc-5-o-slc-500-a-logix-5000-esp
Conversion plc-5-o-slc-500-a-logix-5000-esp
giomar bolivar
 
25.3.10 Packet Tracer - Explore a NetFlow Implementation.docx
25.3.10 Packet Tracer - Explore a NetFlow Implementation.docx25.3.10 Packet Tracer - Explore a NetFlow Implementation.docx
25.3.10 Packet Tracer - Explore a NetFlow Implementation.docx
jesus521837
 

Was ist angesagt? (20)

Arduino c++ y puerto serie
Arduino c++ y puerto serieArduino c++ y puerto serie
Arduino c++ y puerto serie
 
Pic Rs232 puerto serie con PIC16F84A
Pic Rs232 puerto serie con PIC16F84APic Rs232 puerto serie con PIC16F84A
Pic Rs232 puerto serie con PIC16F84A
 
Apagar y encender led con arduino y visual studio 2015
Apagar y encender led con arduino y visual studio 2015Apagar y encender led con arduino y visual studio 2015
Apagar y encender led con arduino y visual studio 2015
 
Tutorial básico control puerto paralelo con visual basic 6.0
Tutorial básico control puerto paralelo con visual basic 6.0Tutorial básico control puerto paralelo con visual basic 6.0
Tutorial básico control puerto paralelo con visual basic 6.0
 
1.2.4.5 packet tracer network representation - ilm
1.2.4.5 packet tracer   network representation - ilm1.2.4.5 packet tracer   network representation - ilm
1.2.4.5 packet tracer network representation - ilm
 
Manual de Operação Primme Acesso Henry - LojaTotalseg.com.br
Manual de Operação Primme Acesso Henry - LojaTotalseg.com.brManual de Operação Primme Acesso Henry - LojaTotalseg.com.br
Manual de Operação Primme Acesso Henry - LojaTotalseg.com.br
 
CONTADOR BINARIO ASCENDENTE DE 14 BITS CON ARDUINO
CONTADOR BINARIO ASCENDENTE DE 14 BITS CON ARDUINOCONTADOR BINARIO ASCENDENTE DE 14 BITS CON ARDUINO
CONTADOR BINARIO ASCENDENTE DE 14 BITS CON ARDUINO
 
Compuertas logicas
Compuertas logicasCompuertas logicas
Compuertas logicas
 
Ps2 sony manual
Ps2 sony  manualPs2 sony  manual
Ps2 sony manual
 
Contador de decadas
Contador de decadasContador de decadas
Contador de decadas
 
Informe 7- Sensores y Transductores - Sensor de Nivel Discreto
Informe 7- Sensores y Transductores - Sensor de Nivel DiscretoInforme 7- Sensores y Transductores - Sensor de Nivel Discreto
Informe 7- Sensores y Transductores - Sensor de Nivel Discreto
 
Manual de Operação Prisma E Henry - LojaTotalseg.com.br
Manual de Operação Prisma E Henry - LojaTotalseg.com.brManual de Operação Prisma E Henry - LojaTotalseg.com.br
Manual de Operação Prisma E Henry - LojaTotalseg.com.br
 
Trabajo sobre Flip Flop
Trabajo sobre Flip FlopTrabajo sobre Flip Flop
Trabajo sobre Flip Flop
 
GUIA BASICA ARDUINO
GUIA BASICA ARDUINOGUIA BASICA ARDUINO
GUIA BASICA ARDUINO
 
Lenze manual global drive gdc en
Lenze manual global drive gdc enLenze manual global drive gdc en
Lenze manual global drive gdc en
 
Arduino: Display de 7 segmentos y como crear un dado electrónico
Arduino: Display de 7 segmentos y como crear un dado electrónicoArduino: Display de 7 segmentos y como crear un dado electrónico
Arduino: Display de 7 segmentos y como crear un dado electrónico
 
Arduino
ArduinoArduino
Arduino
 
Conversion plc-5-o-slc-500-a-logix-5000-esp
Conversion plc-5-o-slc-500-a-logix-5000-espConversion plc-5-o-slc-500-a-logix-5000-esp
Conversion plc-5-o-slc-500-a-logix-5000-esp
 
Fuentes de alimentación de televisores de origen chino
Fuentes de alimentación de televisores de origen chinoFuentes de alimentación de televisores de origen chino
Fuentes de alimentación de televisores de origen chino
 
25.3.10 Packet Tracer - Explore a NetFlow Implementation.docx
25.3.10 Packet Tracer - Explore a NetFlow Implementation.docx25.3.10 Packet Tracer - Explore a NetFlow Implementation.docx
25.3.10 Packet Tracer - Explore a NetFlow Implementation.docx
 

Ähnlich wie Entrada digital con arduino y visual studio 2015

Arduino
ArduinoArduino
Arduino
jjjss
 

Ähnlich wie Entrada digital con arduino y visual studio 2015 (20)

Curso arduino basico bitbloq
Curso arduino basico bitbloqCurso arduino basico bitbloq
Curso arduino basico bitbloq
 
Programación básica de Arduino
Programación básica de Arduino Programación básica de Arduino
Programación básica de Arduino
 
03-arduino.pdf
03-arduino.pdf03-arduino.pdf
03-arduino.pdf
 
Manual basico arduino
Manual basico arduinoManual basico arduino
Manual basico arduino
 
Interfaz java y arduino
Interfaz java y arduinoInterfaz java y arduino
Interfaz java y arduino
 
Arduino
ArduinoArduino
Arduino
 
PDF OP DE KRISTI
PDF OP DE KRISTIPDF OP DE KRISTI
PDF OP DE KRISTI
 
Arduino
ArduinoArduino
Arduino
 
Arduino
ArduinoArduino
Arduino
 
Arduino
ArduinoArduino
Arduino
 
Manual de Arduino
Manual de ArduinoManual de Arduino
Manual de Arduino
 
Interfaz visual basic 6 y arduino
Interfaz visual basic 6 y arduinoInterfaz visual basic 6 y arduino
Interfaz visual basic 6 y arduino
 
Interfaz visual basic 6 y arduino
Interfaz visual basic 6 y arduinoInterfaz visual basic 6 y arduino
Interfaz visual basic 6 y arduino
 
Presentación Fuente interactiva concurso Smart Cities
Presentación Fuente interactiva concurso Smart CitiesPresentación Fuente interactiva concurso Smart Cities
Presentación Fuente interactiva concurso Smart Cities
 
Netduino
NetduinoNetduino
Netduino
 
DISEÑO DE UN DETECTOR DE VELOCIDAD CON ARDUINO
DISEÑO DE UN DETECTOR DE VELOCIDAD CON ARDUINODISEÑO DE UN DETECTOR DE VELOCIDAD CON ARDUINO
DISEÑO DE UN DETECTOR DE VELOCIDAD CON ARDUINO
 
Arduino: programación básica de Arduino
Arduino: programación básica de ArduinoArduino: programación básica de Arduino
Arduino: programación básica de Arduino
 
Biicode hacklab bq
Biicode hacklab bqBiicode hacklab bq
Biicode hacklab bq
 
Cargando el primer programa de arduino
Cargando el primer programa de arduinoCargando el primer programa de arduino
Cargando el primer programa de arduino
 
Trabajo final.
Trabajo final.Trabajo final.
Trabajo final.
 

Mehr von Ángel Acaymo M. G.

Desbloquear impresora Brother MFC-440CN error 46
Desbloquear impresora Brother MFC-440CN error 46Desbloquear impresora Brother MFC-440CN error 46
Desbloquear impresora Brother MFC-440CN error 46
Ángel Acaymo M. G.
 

Mehr von Ángel Acaymo M. G. (10)

Arduino mfc y puerto serie
Arduino mfc y puerto serieArduino mfc y puerto serie
Arduino mfc y puerto serie
 
Arduino delphi tokio 10.2 y puerto serie
Arduino delphi tokio 10.2 y puerto serieArduino delphi tokio 10.2 y puerto serie
Arduino delphi tokio 10.2 y puerto serie
 
Formulario windows con visual c++ 2017
Formulario windows con visual c++ 2017Formulario windows con visual c++ 2017
Formulario windows con visual c++ 2017
 
Formulario windows con visual c++
Formulario windows con visual c++Formulario windows con visual c++
Formulario windows con visual c++
 
Crear formulario windows form con visual c++ 2015
Crear formulario windows form con visual c++ 2015Crear formulario windows form con visual c++ 2015
Crear formulario windows form con visual c++ 2015
 
Rom laboratory
Rom laboratoryRom laboratory
Rom laboratory
 
Desbloquear impresora Brother MFC-440CN error 46
Desbloquear impresora Brother MFC-440CN error 46Desbloquear impresora Brother MFC-440CN error 46
Desbloquear impresora Brother MFC-440CN error 46
 
Teensy++2.0
Teensy++2.0Teensy++2.0
Teensy++2.0
 
Interfaz puerto paralelo LPT
Interfaz puerto paralelo LPTInterfaz puerto paralelo LPT
Interfaz puerto paralelo LPT
 
Mplab Inicio Rapido
Mplab Inicio RapidoMplab Inicio Rapido
Mplab Inicio Rapido
 

Kürzlich hochgeladen

redes informaticas en una oficina administrativa
redes informaticas en una oficina administrativaredes informaticas en una oficina administrativa
redes informaticas en una oficina administrativa
nicho110
 

Kürzlich hochgeladen (12)

investigación de los Avances tecnológicos del siglo XXI
investigación de los Avances tecnológicos del siglo XXIinvestigación de los Avances tecnológicos del siglo XXI
investigación de los Avances tecnológicos del siglo XXI
 
Avances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estosAvances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estos
 
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptxEL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
 
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
 
Buenos_Aires_Meetup_Redis_20240430_.pptx
Buenos_Aires_Meetup_Redis_20240430_.pptxBuenos_Aires_Meetup_Redis_20240430_.pptx
Buenos_Aires_Meetup_Redis_20240430_.pptx
 
redes informaticas en una oficina administrativa
redes informaticas en una oficina administrativaredes informaticas en una oficina administrativa
redes informaticas en una oficina administrativa
 
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptxPROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
 
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptxEVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
 
How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.
 
Avances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvanaAvances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvana
 
Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21
 
pruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITpruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNIT
 

Entrada digital con arduino y visual studio 2015

  • 1. Ángel Acaymo M. G. Electrónica PIC http://electronica-pic.blogspot.com.es Lectura de entradas digitales con Arduino y Visual Studio 2015
  • 2. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 1 Índice ¿Qué puerto uso? ………………………………………………………………………………………………..…………. 3. Códigos 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. Vídeos …………………………………………………………………………………………………………………………..… 121. Enlaces ………………………………………………………………………………………………………………………….. 123. Autor ……………………………………………………………………………………………………………………..……….. 124.
  • 3. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 2 En esta ocasión 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 tecnologías disponibles como Visual C#, Visual C++, Visual Basic .net, WPF C# y WPF VB. No olvidar que también les vale Visual Studio Express 2015, en general es la versión más capada, lo que necesitamos en este momento lo incluye sin problemas. Hay dos códigos 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 más encender Arduino o Resetearlo, a parte que muestra la información 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 códigos fuentes de ejemplos de Visual Studio, Arduino e imágenes de los Led: Enlace Enlace
  • 4. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 3 ¿Qué puerto uso? Para saber que puerto estamos usando con Arduino. Entras desde Windows “InicioPanel de controlTodos los elementos de Panel de controlSistema”. Luego pulsas “Administrador de dispositivos”.
  • 5. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 4 En mi caso usaré el COM4, en tu caso puede ser diferente, así que para todo usarás el que te haya tocado.
  • 6. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 5 Haz doble clic en Arduino UNO (COM4) para mostrar la ventana Propiedades: Arduino UNO (COM4). En este caso para todo usaré la configuración que obtienes en la imagen, tanto para Arduino UNO, en el Monitor Serie, en tu interfaz hecho con Visual Studio y en el código de Arduino.
  • 7. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 6
  • 8. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 7 Códigos 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 botón 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 número 8. // Si el pulsador está pulsado, se enciende el Led 13 y // envía comando HIGH por el puerto serie. if(estadoBoton != anteriorBoton) // Comprueba si ha habido un cambio en el estado del botón. { flagMensaje = 0; // Resetea la bandera a 0. anteriorBoton = estadoBoton; // Guarda el estado actual del botón. } if (estadoBoton == HIGH && flagMensaje == 0) // Comprueba que el botón 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 próxima vez. flagMensaje++; }
  • 9. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 8 // De lo contrario, Led 13 apagado y envía LOW al puerto serie. else if(flagMensaje == 0) // Si el botón no está presionado y aún no se envía 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 próxima vez. flagMensaje++; } }
  • 10. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 9 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 físicamente Arduino UNO, también muestra los últimos interruptores que tienes activados o no en ese momento. Si ejecutas a aplicación, de entrada no muestra nada, pulsas el botón “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); }
  • 11. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 10 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");
  • 12. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 11 Serial.println(buffer); estadoBotonAnt1 = estadoBoton1; estadoBotonAnt2 = estadoBoton2; estadoBotonAnt3 = estadoBoton3; estadoBotonAnt4 = estadoBoton4; }
  • 13. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 12 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); }
  • 14. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 13 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; }
  • 15. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 14
  • 16. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 15 Visual C# AWF 2015
  • 17. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 16 Ejemplo 1: Este ejemplo corresponde al código del Ejemplo 1 de Arduino. Creamos un proyecto nuevo con Visual C#. Selecciona Entorno clásico en Visual C#, Aplicación de Windows Forms, he puesto como nombre del proyecto en este caso Entrada_Arduino_AWF_1_CS, luego pulsar Aceptar.
  • 18. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 17 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
  • 19. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 18 Seguimos en el componente PictureBox, pulsamos … en la propiedad Image como indica abajo para introducir dos imágenes de dos Led, encendido y apagado.
  • 20. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 19 Se abre un cuadro llamado Seleccionar recurso en el cual podemos añadir las imágenes que queramos. Pulsamos el botón Importar… y elegimos las imágenes de Leds que queramos, en este caso selecciono el rojo apagado y encendido.
  • 21. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 20 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.
  • 22. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 21 Añade el componente SerialPort haciendo doble clic en él o arrastrándolo al formulario.
  • 23. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 22 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.
  • 24. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 23 Tener claro estas líneas al recibir datos desde Arduino como ON y OFF.
  • 25. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 24 Ejemplo 1: Código 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 recepción. 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)); }
  • 26. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 25 // 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 aplicación. private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (serialPort1.IsOpen) // ¿El puerto está abierto? { serialPort1.Close(); // Cerrar puerto. } } } }
  • 27. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 26 Ejemplo 2: Este ejemplo corresponde al código 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.
  • 28. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 27 Código 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 recepción. 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)); }
  • 29. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 28 // 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 posición 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"); // Envía comando ACTUALIZAR por el puerto. serialPort1.Write(mBuffer, 0, mBuffer.Length); } private void Form1_Load(object sender, EventArgs e) { Actualizar(); } } }
  • 30. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 29 Ejemplo 3: Este ejemplo corresponde al código del Ejemplo 3 de Arduino. Se trata en este caso unir los dos ejemplos de Visual Studio, las imágenes de los Leds y mostrar mensajes en el richTextBox. Se recomienda mirar el primer ejemplo para seguir bien la guía o entender el concepto si eres muy novel.
  • 31. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 30 Código 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 recepción. 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 posición final para leer los mensajes entrantes. richTextBox1.SelectionStart = richTextBox1.Text.Length; // Mantiene el scroll en la entrada de cada mensaje. richTextBox1.ScrollToCaret();
  • 32. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 31 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"; }
  • 33. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 32 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"); // Envía 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 = ""; } } }
  • 34. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 33
  • 35. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 34 Visual C# WPF 2015
  • 36. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 35 Creamos un proyecto nuevo con Visual C#. Como nombre en este caso lo he llamado Entrada_Arduino_WPF_1_CS.
  • 37. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 36 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
  • 38. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 37 Seguimos en el componente image, pulsamos … en la propiedad Image como indica abajo, Proyecto  Agregar elemento existente… Podemos seleccionar las imágenes que queremos, en este caso he elegido el Led apagado y el otro encendido de color rojo. Para finalizar, pulsa el botón Agregar.
  • 39. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 38 En la propiedad Source, eliges el Led rojo apagado, si lo deseas, puede escoger el verde, pero que sea apagado.
  • 40. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 39 Tener claro estas líneas al recibir datos desde Arduino como ON y OFF.
  • 41. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 40 Ejemplo 1: Código 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> /// Lógica de interacción para MainWindow.xaml /// </summary> public partial class MainWindow : Window { // Utilizaremos un string como buffer de recepción. 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 aplicación. if (!serialPort1.IsOpen) { try { serialPort1.Open(); } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } }
  • 42. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 41 // Ejecutar la función Recepción 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. } } } }
  • 43. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 42 Este ejemplo corresponde al código 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.
  • 44. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 43 Ejemplo 2: Código 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> /// Lógica de interacción para MainWindow.xaml /// </summary> public partial class MainWindow : Window { // Utilizaremos un string como buffer de recepción. 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 aplicación. if (!serialPort1.IsOpen) { try { serialPort1.Open(); } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } }
  • 45. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 44 // Ejecutar la función Recepción 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"); // Envía 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. } } } }
  • 46. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 45 Ejemplo 3: Este ejemplo corresponde al código del Ejemplo 3 de Arduino. Se trata en este caso unir los dos ejemplos de Visual Studio, las imágenes de los Leds y mostrar mensajes en el richTextBox. Se recomienda mirar el primer ejemplo para seguir bien la guía o entender el concepto si eres muy novel.
  • 47. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 46 Ejemplo 3: Código 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> /// Lógica de interacción para MainWindow.xaml /// </summary> public partial class MainWindow : Window { // Utilizaremos un string como buffer de recepción. 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 aplicación. if (!serialPort1.IsOpen) { try { serialPort1.Open(); } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } }
  • 48. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 47 // Ejecutar la función Recepción 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;
  • 49. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 48 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"); // Envía 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. } } } }
  • 50. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 49
  • 51. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 50 Visual Basic AWF 2015
  • 52. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 51 Ejemplo 1: Este ejemplo corresponde al código del Ejemplo 1 de Arduino. Creamos un proyecto nuevo con Visual Basic. Selecciona Entorno clásico en Visual Basic, Aplicación de Windows Forms, he puesto como nombre del proyecto en este caso Entrada_Arduino_AWF_1_VB, luego pulsar Aceptar.
  • 53. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 52 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
  • 54. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 53 Seguimos en el componente PictureBox, pulsamos … en la propiedad Image como indica abajo para introducir dos imágenes de dos Led, encendido y apagado.
  • 55. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 54 Se abre un cuadro llamado Seleccionar recurso en el cual podemos añadir las imágenes que queramos. Pulsamos el botón Importar… y elegimos las imágenes de Leds que queramos, en este caso selecciono el rojo apagado y encendido.
  • 56. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 55 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.
  • 57. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 56 Añade el componente SerialPort haciendo doble clic en él o arrastrándolo al formulario.
  • 58. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 57 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.
  • 59. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 58 Tener claro estas líneas al recibir datos desde Arduino como ON y OFF.
  • 60. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 59 Ejemplo 1: Código 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 recepción. 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 función 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
  • 61. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 60 Ejemplo 2: Este ejemplo corresponde al código 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.
  • 62. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 61 Imports System.IO.Ports ' No olvidar. Imports System.Text Imports System.Threading Public Class Form1 ' Utilizaremos un string como buffer de recepción. 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 función 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 posición 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") ' Envía 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
  • 63. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 62 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
  • 64. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 63 Ejemplo 3: Este ejemplo corresponde al código del Ejemplo 3 de Arduino. Se trata en este caso unir los dos ejemplos de Visual Studio, las imágenes de los Leds y mostrar mensajes en el richTextBox. Se recomienda mirar el primer ejemplo para seguir bien la guía o entender el concepto si eres muy novel.
  • 65. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 64 Imports System.IO.Ports ' No olvidar. Imports System.Text Imports System.Threading Public Class Form1 ' Utilizaremos un string como buffer de recepción. 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 función 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 posición 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)
  • 66. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 65 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") ' Envía 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.
  • 67. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 66 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
  • 68. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 67
  • 69. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 68 Visual Basic WPF 2015
  • 70. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 69 Creamos un proyecto nuevo con Visual Basic. Como nombre en este caso lo he llamado Entrada_Arduino_WPF_1_VB.
  • 71. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 70 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
  • 72. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 71 Seguimos en el componente image, pulsamos … en la propiedad Image como indica abajo, Proyecto  Agregar elemento existente… Podemos seleccionar las imágenes que queremos, en este caso he elegido el Led apagado y el otro encendido de color rojo. Para finalizar, pulsa el botón Agregar. En la propiedad Source, eliges el Led rojo apagado, si lo deseas, puede escoger el verde, pero que sea apagado.
  • 73. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 72
  • 74. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 73 Tener claro estas líneas al recibir datos desde Arduino como ON y OFF.
  • 75. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 74 Ejemplo 1: Código 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 recepción. 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 aplicación. If Not serialPort1.IsOpen Then Try serialPort1.Open() Catch ex As System.Exception MessageBox.Show(ex.ToString()) End Try End If ' Ejecutar la función Recepción 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)))
  • 76. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 75 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
  • 77. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 76 Este ejemplo corresponde al código 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.
  • 78. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 77 Ejemplo 2: Código 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 recepción. 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 aplicación. If Not serialPort1.IsOpen Then Try serialPort1.Open() Catch ex As System.Exception MessageBox.Show(ex.ToString()) End Try End If ' Ejecutar la función Recepción 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
  • 79. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 78 Private Sub Actualizar_estados() Dim miBuffer As Byte() = Encoding.ASCII.GetBytes("ACTUALIZAR") ' Envía 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
  • 80. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 79 Ejemplo 3: Este ejemplo corresponde al código del Ejemplo 3 de Arduino. Se trata en este caso unir los dos ejemplos de Visual Studio, las imágenes de los Leds y mostrar mensajes en el richTextBox. Se recomienda mirar el primer ejemplo para seguir bien la guía o entender el concepto si eres muy novel.
  • 81. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 80 Ejemplo 3: Código 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 recepción. 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 aplicación. If Not serialPort1.IsOpen Then Try serialPort1.Open() Catch ex As System.Exception MessageBox.Show(ex.ToString()) End Try End If ' Ejecutar la función Recepción 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}
  • 82. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 81 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") ' Envía comando ACTUALIZAR por el puerto. serialPort1.Write(miBuffer, 0, miBuffer.Length) End Sub
  • 83. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 82 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
  • 84. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 83
  • 85. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 84 Visual C++ CLR 2015
  • 86. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 85 Antes de empezar, hay que instalar las herramientas comunes para Visual C++ 2015 como indica la imagen.
  • 87. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 86 Cuando tengas Visual Studio Community 2015 ya ejecutado, creamos un proyecto nuevo. ArchivoNuevoProyecto… Mirar imagen grande en la página siguiente.
  • 88. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 87 Le ventana Nuevo proyecto está abierta y seguimos en orden lo que indica la imagen. 1) Visual C++ en Plantillas. 2) CLR. 3) Proyecto vacío de CLR. 4) Ponemos el nombre que queramos, en este caso lo he llamado Entrada_Arduino_CPP_CLR_1. 5) Pulsamos Aceptar.
  • 89. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 88 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.
  • 90. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 89 Como muestra la imagen de abajo. Cloqueamos en Visual C++ UI y Señalamos Windows Forms, le he añadido como nombre en el tercer paso Form_Principal, puedes poner cualquier nombre, al final, pulsa Aceptar.
  • 91. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 90 En mi caso puede ver que hay un mensaje de error como muestra en esta imagen y en la página siguiente. No preocuparse, aún no hemos acabado.
  • 92. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 91 Cierra la pestaña pulsando la X. En la página siguiente lo volverás a abrir con el formulario.
  • 93. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 92 Indicamos en el “Explorador de soluciones”, hacemos clic en el botón derecho del ratón y luego pulsamos “Propiedades”.
  • 94. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 93 Sigue el procedimiento indicado abajo, en Subsistema tiene que ser Windows (/SUBSYSTEM:WINDOWS), luego pulsas aplicar.
  • 95. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 94 Vete a la pestaña “Avanzadas”, Punto de entrada escribes main. Finalmente el botón Aceptar.
  • 96. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 95 Escribe los códigos necesarios como muestra en la imagen, pero antes, mira la página siguiente que se ve más grande y mejor.
  • 97. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 96 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
  • 98. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 97 Seguimos en el componente PictureBox, pulsamos … en la propiedad Image como indica abajo para introducir dos imágenes de dos Led, encendido y apagado.
  • 99. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 98 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.
  • 100. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 99 Añade el componente SerialPort haciendo doble clic en él o arrastrándolo al formulario.
  • 101. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 100 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.
  • 102. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 101 Tener claro estas líneas al recibir datos desde Arduino como ON y OFF.
  • 103. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 102 Ejemplo 1: Código 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 recepción. String^ Recibidos; public: Form_Principal(void) { InitializeComponent(); // //TODO: agregar código 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)); }
  • 104. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 103 // 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("LedLed_rojo_encendido.png"); Recibidos = ""; } else { panel1->BackColor = Color::Red; label_Lectura->Text = "Desactivado"; pictureBox_Dibujo->Load("LedLed_rojo_apagado.png"); Recibidos = ""; } } protected: /// <summary> /// Limpiar los recursos que se estén 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 diseñador necesaria. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Método necesario para admitir el Diseñador. No se puede modificar /// el contenido de este método con el editor de código. /// </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());
  • 105. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 104 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
  • 106. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 105 // 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"Electrónica 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. } } }; }
  • 107. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 106 Ejemplo 2: Este ejemplo corresponde al código 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.
  • 108. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 107 Código 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 recepción. 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;
  • 109. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 108 // Selecciona la posición 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 estén 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 diseñador necesaria. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Método necesario para admitir el Diseñador. No se puede modificar /// el contenido de este método con el editor de código. /// </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);
  • 110. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 109 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;
  • 111. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 110 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"Electrónica 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"); // Envía 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. } }
  • 112. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 111 private: System::Void Form_Principal_Load(System::Object^ sender, System::EventArgs^ e) { Actualizar(); } }; }
  • 113. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 112 Ejemplo 3: Este ejemplo corresponde al código del Ejemplo 3 de Arduino. Se trata en este caso unir los dos ejemplos de Visual Studio, las imágenes de los Leds y mostrar mensajes en el richTextBox. Se recomienda mirar el primer ejemplo para seguir bien la guía o entender el concepto si eres muy novel.
  • 114. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 113 Código 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 recepción. 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)
  • 115. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 114 { // Asignar el valor de la trama al richTextBox. richTextBox1->Text += Recibidos; // Selecciona la posición 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("LedLed_rojo_encendido.png"); else if (Comandos == "1=OFF") pictureBox1->Load("LedLed_rojo_apagado.png"); else if (Comandos == "2=ON") pictureBox2->Load("LedLed_rojo_encendido.png"); else if (Comandos == "2=OFF") pictureBox2->Load("LedLed_rojo_apagado.png"); else if (Comandos == "3=ON") pictureBox3->Load("LedLed_rojo_encendido.png"); else if (Comandos == "3=OFF") pictureBox3->Load("LedLed_rojo_apagado.png"); else if (Comandos == "4=ON") pictureBox4->Load("LedLed_rojo_encendido.png"); else if (Comandos == "4=OFF") pictureBox4->Load("LedLed_rojo_apagado.png"); Recibidos = ""; } richTextBox1->Text += " " + DateTime::Now.ToString() + "r"; } // ################################################################################# ############################### protected: /// <summary> /// Limpiar los recursos que se estén 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;
  • 116. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 115 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 diseñador necesaria. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Método necesario para admitir el Diseñador. No se puede modificar /// el contenido de este método con el editor de código. /// </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();
  • 117. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 116 (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 //
  • 118. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 117 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"; //
  • 119. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 118 // 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);
  • 120. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 119 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"Electrónica 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"); // Envía 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. }
  • 121. LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015 Electrónica PIC | http://electronica-pic.blogspot.com.es 120 } private: System::Void Form_Principal_Load(System::Object^ sender, System::EventArgs^ e) { Actualizar(); } }; }