Академический Документы
Профессиональный Документы
Культура Документы
ngel Acaymo M. G.
Electrnica PIC
http://electronica-pic.blogspot.com.es
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
ndice
En esta ocasin se trata de leer las entradas digitales de Arduino UNO r3 y mostrar los
resultados con tu propia interfaz hecha bajo Visual Studio Community 2015 en cualquiera de
los lenguajes y tecnologas disponibles como Visual C#, Visual C++, Visual Basic .net, WPF C# y
WPF VB. No olvidar que tambin les vale Visual Studio Express 2015, en general es la versin
ms capada, lo que necesitamos en este momento lo incluye sin problemas.
Hay dos cdigos de ejemplo en Arduino. De los 4 interruptores como entradas digitales que
vamos a usar, muestra los resultados en Visual Studio en forma de cambiar los colores como
un panel de verde si est activado, rojo si est apagado, un label que indica palabra como
Activado, Desactivado y una imagen con pictureBox cuando muestra un Led en forma de
dibujo apagado y el otro encendido.
El otro ejemplo de Arduino se trata de comprobar los estados de los interruptores nada ms
encender Arduino o Resetearlo, a parte que muestra la informacin en el componente
richTextBox en Visual Studio.
https://www.visualstudio.com/es-es/products/visual-studio-community-vs.aspx
https://www.visualstudio.com/es-es/products/visual-studio-express-vs.aspx
https://www.arduino.cc/en/Main/Software
Descargar cdigos fuentes de ejemplos de Visual Studio, Arduino e imgenes de los Led:
Enlace
Enlace
Qu puerto uso?
Para saber que puerto estamos usando con Arduino.
Entras desde Windows Inicio\Panel de control\Todos los elementos de Panel de
control\Sistema.
Luego pulsas Administrador de dispositivos.
En mi caso usar el COM4, en tu caso puede ser diferente, as que para todo usars el que te
haya tocado.
Haz doble clic en Arduino UNO (COM4) para mostrar la ventana Propiedades: Arduino UNO
(COM4). En este caso para todo usar la configuracin que obtienes en la imagen, tanto para
Arduino UNO, en el Monitor Serie, en tu interfaz hecho con Visual Studio y en el cdigo de
Arduino.
Cdigos de Arduino
Ejemplo Arduino 1:
Entrada digital con Arduino y Visual Studio 2015. Muestra los estados de las entradas digitales
en componentes Panel, label y pictureBox de Visual Studio.
void setup()
{
pinMode(13,OUTPUT); // Donde est el Led 13.
pinMode(8,INPUT); // Entrada digital donde est el pulsador.
Serial.begin(115200);
}
void loop()
{
estadoBoton=digitalRead(8); // Leer entrada digital nmero 8.
if (estadoBoton == HIGH && flagMensaje == 0) // Comprueba que el botn est pulsado y que
no se haya enviado el mensaje.
digitalWrite(13,HIGH);
Serial.write("ON");
delay(50);
flagMensaje++;
}
Electrnica PIC | http://electronica-pic.blogspot.com.es 7
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
digitalWrite(13,LOW);
Serial.write("OFF");
delay(50);
flagMensaje++;
Ejemplo Arduino 2:
void setup()
void loop() {
leeEstado();
if ((estadoBoton1 != estadoBotonAnt1) ||
(estadoBoton2 != estadoBotonAnt2) ||
(estadoBoton3 != estadoBotonAnt3) ||
(estadoBoton4 != estadoBotonAnt4))
printEstado();
delay(50);
{
caracter= Serial.read();
comando.concat(caracter);
delay(10);
}
if (comando.equals("ACTUALIZAR") == true)
printEstado();
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");
Serial.println(buffer);
estadoBotonAnt1 = estadoBoton1;
estadoBotonAnt2 = estadoBoton2;
estadoBotonAnt3 = estadoBoton3;
estadoBotonAnt4 = estadoBoton4;
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);
caracter= Serial.read();
comando.concat(caracter);
delay(10);
if (comando.equals("ACTUALIZAR") == true)
printEstado();
comando="";
// Funciones.
void leeEstado()
{
estadoBoton1 = digitalRead(8);
estadoBoton2 = digitalRead(7);
estadoBoton3 = digitalRead(6);
estadoBoton4 = digitalRead(5);
void printEstado(void)
digitalWrite(13,estadoBoton1);
digitalWrite(12,estadoBoton2);
digitalWrite(11,estadoBoton3);
digitalWrite(10,estadoBoton4);
sprintf(buffer,"%s %s %s %s",
estadoBoton1?"1=ON":"1=OFF",
estadoBoton2?"2=ON":"2=OFF",
estadoBoton3?"3=ON":"3=OFF",
estadoBoton4?"4=ON":"4=OFF");
Serial.print(buffer);
estadoBotonAnt1 = estadoBoton1;
estadoBotonAnt2 = estadoBoton2;
estadoBotonAnt3 = estadoBoton3;
estadoBotonAnt4 = estadoBoton4;
}
Electrnica PIC | http://electronica-pic.blogspot.com.es 13
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Ejemplo 1:
Selecciona Entorno clsico en Visual C#, Aplicacin de Windows Forms, he puesto como
nombre del proyecto en este caso Entrada_Arduino_AWF_1_CS, luego pulsar Aceptar.
Panel:
Propiedad Cambie a
BorderStyle FixedSingle
Label:
Propiedad Cambie a
(Name) Label_Entrada
Text Leyendo...
PictureBox:
Propiedad Cambie a
(Name) pictureBox_Dibujo
SizeMode StretchImage
Se abre un cuadro llamado Seleccionar recurso en el cual podemos aadir las imgenes que
queramos.
Pulsamos el botn Importar y elegimos las imgenes de Leds que queramos, en este caso
selecciono el rojo apagado y encendido.
Pulsa Aceptar.
Dejar claro que en la propiedad SizeMode del PicturreBox le he puesto StretchImage par
redimensionar el dibujo o imagen al cuadro.
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.
Tener claro estas lneas al recibir datos desde Arduino como ON y OFF.
Ejemplo 1:
namespace Entrada_Arduino_AWF_1_CS
{
public partial class Form1 : Form
{
// Utilizaremos un string como buffer de recepcin.
string Recibidos;
public Form1()
{
InitializeComponent();
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
serialPort1.DataReceived += new
SerialDataReceivedEventHandler(Recepcion);
}
}
// Al recibir datos.
private void Recepcion(object sender, SerialDataReceivedEventArgs e)
{
// Acumula los caracteres recibidos a nuestro 'buffer' (string).
Recibidos += serialPort1.ReadExisting();
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;
}
}
Ejemplo 2:
Si has llegado aqu directamente, se recomienda leer paso a paso el primer ejemplo.
namespace Entrada_Arduino_AWF_2_CS
{
public partial class Form1 : Form
{
// Utilizaremos un string como buffer de recepcin.
string Recibidos;
public Form1()
{
InitializeComponent();
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
serialPort1.DataReceived += new
SerialDataReceivedEventHandler(Recepcion);
}
}
// Al recibir datos.
private void Recepcion(object sender, SerialDataReceivedEventArgs e)
{
// Acumula los caracteres recibidos a nuestro 'buffer' (string).
Recibidos += serialPort1.ReadExisting();
void Actualizar()
{
byte[] mBuffer = Encoding.ASCII.GetBytes("ACTUALIZAR"); // Enva
comando ACTUALIZAR por el puerto.
serialPort1.Write(mBuffer, 0, mBuffer.Length);
}
Ejemplo 3:
Se trata en este caso unir los dos ejemplos de Visual Studio, las imgenes de los Leds y mostrar
mensajes en el richTextBox.
Se recomienda mirar el primer ejemplo para seguir bien la gua o entender el concepto si eres
muy novel.
namespace Entrada_Arduino_AWF_3_CS
{
public partial class Form1 : Form
{
// Utilizaremos un string como buffer de recepcin.
string Recibidos;
public Form1()
{
InitializeComponent();
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
serialPort1.DataReceived += new
SerialDataReceivedEventHandler(Recepcion);
}
}
// Al recibir datos.
private void Recepcion(object sender, SerialDataReceivedEventArgs e)
{
// Acumula los caracteres recibidos a nuestro 'buffer' (string).
Recibidos += serialPort1.ReadExisting();
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;
}
}
void Actualizar()
{
byte[] mBuffer = Encoding.ASCII.GetBytes("ACTUALIZAR"); // Enva
comando ACTUALIZAR por el puerto.
serialPort1.Write(mBuffer, 0, mBuffer.Length);
}
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
Podemos seleccionar las imgenes que queremos, en este caso he elegido el Led apagado y el
otro encendido de color rojo. Para finalizar, pulsa el botn Agregar.
En la propiedad Source, eliges el Led rojo apagado, si lo deseas, puede escoger el verde, pero
que sea apagado.
Tener claro estas lneas al recibir datos desde Arduino como ON y OFF.
Ejemplo 1:
namespace Entrada_Arduino_WPF_1_CS
{
/// <summary>
/// Lgica de interaccin para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
// Utilizaremos un string como buffer de recepcin.
string Recibidos;
SerialPort serialPort1 = new SerialPort();
public MainWindow()
{
InitializeComponent();
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;
}
}
}
}
}
Si has llegado aqu directamente, se recomienda leer paso a paso el primer ejemplo.
Ejemplo 2:
namespace Entrada_Arduino_WPF_2_CS
{
/// <summary>
/// Lgica de interaccin para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
// Utilizaremos un string como buffer de recepcin.
string Recibidos;
SerialPort serialPort1 = new SerialPort();
public MainWindow()
{
InitializeComponent();
void Actualizar_estados()
{
byte[] miBuffer = Encoding.ASCII.GetBytes("ACTUALIZAR"); // Enva
comando ACTUALIZAR por el puerto.
serialPort1.Write(miBuffer, 0, miBuffer.Length);
}
Ejemplo 3:
Se trata en este caso unir los dos ejemplos de Visual Studio, las imgenes de los Leds y mostrar
mensajes en el richTextBox.
Se recomienda mirar el primer ejemplo para seguir bien la gua o entender el concepto si eres
muy novel.
Ejemplo 3:
namespace Entrada_Arduino_WPF_3_CS
{
/// <summary>
/// Lgica de interaccin para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
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;
case "3=ON":
image_3.Source = (new BitmapImage(new Uri("Led rojo
encendido.png", UriKind.Relative)));
Recibidos = ""; // Limpiar.
break;
case "3=OFF":
image_3.Source = (new BitmapImage(new Uri("Led rojo
apagado.png", UriKind.Relative)));
Recibidos = ""; // Limpiar.
break;
case "4=ON":
image_4.Source = (new BitmapImage(new Uri("Led rojo
encendido.png", UriKind.Relative)));
Recibidos = ""; // Limpiar.
break;
case "4=OFF":
image_4.Source = (new BitmapImage(new Uri("Led rojo
apagado.png", UriKind.Relative)));
Recibidos = ""; // Limpiar.
break;
}
}
}
void Actualizar_estados()
{
byte[] miBuffer = Encoding.ASCII.GetBytes("ACTUALIZAR"); // Enva
comando ACTUALIZAR por el puerto.
serialPort1.Write(miBuffer, 0, miBuffer.Length);
}
Ejemplo 1:
Selecciona Entorno clsico en Visual Basic, Aplicacin de Windows Forms, he puesto como
nombre del proyecto en este caso Entrada_Arduino_AWF_1_VB, luego pulsar Aceptar.
Panel:
Propiedad Cambie a
BorderStyle FixedSingle
Label:
Propiedad Cambie a
(Name) Label_Entrada
Text Leyendo...
PictureBox:
Propiedad Cambie a
(Name) pictureBox_Dibujo
SizeMode StretchImage
Se abre un cuadro llamado Seleccionar recurso en el cual podemos aadir las imgenes que
queramos.
Pulsamos el botn Importar y elegimos las imgenes de Leds que queramos, en este caso
selecciono el rojo apagado y encendido.
Pulsa Aceptar.
Dejar claro que en la propiedad SizeMode del PicturreBox le he puesto StretchImage par
redimensionar el dibujo o imagen al cuadro.
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.
Tener claro estas lneas al recibir datos desde Arduino como ON y OFF.
Ejemplo 1:
End If
End Sub
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
Ejemplo 2:
Si has llegado aqu directamente, se recomienda leer paso a paso el primer ejemplo.
End If
End Sub
End Sub
Ejemplo 3:
Se trata en este caso unir los dos ejemplos de Visual Studio, las imgenes de los Leds y mostrar
mensajes en el richTextBox.
Se recomienda mirar el primer ejemplo para seguir bien la gua o entender el concepto si eres
muy novel.
End If
End Sub
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
End Sub
Recibidos = ""
End Sub
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
Podemos seleccionar las imgenes que queremos, en este caso he elegido el Led apagado y el
otro encendido de color rojo. Para finalizar, pulsa el botn Agregar.
En la propiedad Source, eliges el Led rojo apagado, si lo deseas, puede escoger el verde, pero
que sea apagado.
Electrnica PIC | http://electronica-pic.blogspot.com.es 71
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Tener claro estas lneas al recibir datos desde Arduino como ON y OFF.
Ejemplo 1:
Class MainWindow
' Utilizaremos un string como buffer de recepcin.
Dim Recibidos As String
' Creamos un objeto sdel puerto serie.
Dim serialPort1 As New SerialPort()
End Try
End If
' Ejecutar la funcin Recepcin por disparo del evento DataReived!
AddHandler serialPort1.DataReceived, AddressOf Recepcion
End Sub
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.
Exit Select
End Select
End Sub
Si has llegado aqu directamente, se recomienda leer paso a paso el primer ejemplo.
Ejemplo 2:
Class MainWindow
' Utilizaremos un string como buffer de recepcin.
Dim Recibidos As String
' Creamos un objeto sdel puerto serie.
Dim serialPort1 As New SerialPort()
End Try
End If
' Ejecutar la funcin Recepcin por disparo del evento DataReived!
AddHandler serialPort1.DataReceived, AddressOf Recepcion
End Sub
Ejemplo 3:
Se trata en este caso unir los dos ejemplos de Visual Studio, las imgenes de los Leds y mostrar
mensajes en el richTextBox.
Se recomienda mirar el primer ejemplo para seguir bien la gua o entender el concepto si eres
muy novel.
Ejemplo 3:
Class MainWindow
' Utilizaremos un string como buffer de recepcin.
Dim Recibidos As String
' Creamos un objeto sdel puerto serie.
Dim serialPort1 As New SerialPort()
End Try
End If
' Ejecutar la funcin Recepcin por disparo del evento DataReived!
AddHandler serialPort1.DataReceived, AddressOf Recepcion
End Sub
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
Antes de empezar, hay que instalar las herramientas comunes para Visual C++ 2015 como
indica la imagen.
Le ventana Nuevo proyecto est abierta y seguimos en orden lo que indica la imagen.
1) Visual C++ en Plantillas.
2) CLR.
3) Proyecto vaco de CLR.
4) Ponemos el nombre que queramos, en este caso lo he llamado
Entrada_Arduino_CPP_CLR_1.
5) Pulsamos Aceptar.
En mi caso puede ver que hay un mensaje de error como muestra en esta imagen y en
la pgina siguiente.
No preocuparse, an no hemos acabado.
Escribe los cdigos necesarios como muestra en la imagen, pero antes, mira la
pgina siguiente que se ve ms grande y mejor.
Panel:
Propiedad Cambie a
BorderStyle FixedSingle
Label:
Propiedad Cambie a
(Name) Label_Entrada
Text Leyendo...
PictureBox:
Propiedad Cambie a
(Name) pictureBox_Dibujo
SizeMode StretchImage
Electrnica PIC | http://electronica-pic.blogspot.com.es 96
LECTURA DE ENTRADAS DIGITALES CON ARDUINO Y VISUAL STUDIO 2015
Dejar claro que en la propiedad SizeMode del PicturreBox le he puesto StretchImage par
redimensionar el dibujo o imagen al cuadro.
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.
Tener claro estas lneas al recibir datos desde Arduino como ON y OFF.
Ejemplo 1:
namespace Entrada_Arduino_CPP_CLR_1 {
/// <summary>
/// Resumen de Form_Principal
/// </summary>
public ref class Form_Principal : public System::Windows::Forms::Form
{
// Utilizaremos un string como buffer de recepcin.
String^ Recibidos;
public:
Form_Principal(void)
{
InitializeComponent();
//
//TODO: agregar cdigo de constructor aqu
//
if (!serialPort1->IsOpen)
{
try
{
serialPort1->Open();
}
catch (Exception ^ex)
{
MessageBox::Show(ex->ToString());
}
serialPort1->DataReceived += gcnew
SerialDataReceivedEventHandler(this, &Form_Principal::Recepcion);
}
}
// Al recibir datos.
private: Void Recepcion(Object^ sender,
SerialDataReceivedEventArgs^ e)
{
// Acumula los caracteres recibidos a nuestro 'buffer'
(string).
Recibidos += serialPort1->ReadExisting();
else
{
panel1->BackColor = Color::Red;
label_Lectura->Text = "Desactivado";
pictureBox_Dibujo->Load("Led\\Led_rojo_apagado.png");
Recibidos = "";
}
}
protected:
/// <summary>
/// Limpiar los recursos que se estn usando.
/// </summary>
~Form_Principal()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Label^ label_titulo;
protected:
private: System::Windows::Forms::Panel^ panel1;
private: System::Windows::Forms::Label^ label_Lectura;
private: System::Windows::Forms::PictureBox^ pictureBox_Dibujo;
private: System::IO::Ports::SerialPort^ serialPort1;
private: System::Windows::Forms::Label^ label1;
private: System::ComponentModel::IContainer^ components;
private:
/// <summary>
/// Variable del diseador necesaria.
/// </summary>
(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
//
this->serialPort1->BaudRate = 115200;
this->serialPort1->PortName = L"COM4";
this->serialPort1->StopBits =
System::IO::Ports::StopBits::Two;
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(349, 200);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(25, 13);
this->label1->TabIndex = 4;
this->label1->Text = L"Led";
//
// Form_Principal
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode =
System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(436, 262);
this->Controls->Add(this->label1);
this->Controls->Add(this->pictureBox_Dibujo);
this->Controls->Add(this->label_Lectura);
this->Controls->Add(this->panel1);
this->Controls->Add(this->label_titulo);
this->Name = L"Form_Principal";
this->StartPosition =
System::Windows::Forms::FormStartPosition::CenterScreen;
this->Text = L"Electrnica PIC - C++ 2015";
this->FormClosing += gcnew
System::Windows::Forms::FormClosingEventHandler(this,
&Form_Principal::Form_Principal_FormClosing);
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox_Dibujo))->EndInit();
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void Form_Principal_FormClosing(System::Object^ sender,
System::Windows::Forms::FormClosingEventArgs^ e) {
if (serialPort1->IsOpen) // El puerto est abierto?
{
serialPort1->Close(); // Puerto cerrado.
}
}
};
}
Ejemplo 2:
Si has llegado aqu directamente, se recomienda leer paso a paso el primer ejemplo.
namespace Entrada_Arduino_CPP_CLR_2 {
/// <summary>
/// Resumen de Form_Principal
/// </summary>
public ref class Form_Principal : public System::Windows::Forms::Form
{
public:
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();
protected:
/// <summary>
/// Limpiar los recursos que se estn usando.
/// </summary>
~Form_Principal()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::RichTextBox^ richTextBox1;
protected:
private: System::Windows::Forms::Label^ label_Mensajes_desde_Arduino;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Button^ button_Actualizar;
private: System::Windows::Forms::Button^ button_Limpiar;
private: System::IO::Ports::SerialPort^ serialPort1;
private: System::ComponentModel::IContainer^ components;
private:
/// <summary>
/// Variable del diseador necesaria.
/// </summary>
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;
this->button_Limpiar->Click += gcnew
System::EventHandler(this, &Form_Principal::button_Limpiar_Click);
//
// serialPort1
//
this->serialPort1->BaudRate = 115200;
this->serialPort1->PortName = L"COM4";
this->serialPort1->StopBits =
System::IO::Ports::StopBits::Two;
//
// Form_Principal
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode =
System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(364, 262);
this->Controls->Add(this->button_Limpiar);
this->Controls->Add(this->button_Actualizar);
this->Controls->Add(this->label2);
this->Controls->Add(this->label1);
this->Controls->Add(this->label_Mensajes_desde_Arduino);
this->Controls->Add(this->richTextBox1);
this->Name = L"Form_Principal";
this->StartPosition =
System::Windows::Forms::FormStartPosition::CenterScreen;
this->Text = L"Electrnica PIC- C++ 2015";
this->FormClosing += gcnew
System::Windows::Forms::FormClosingEventHandler(this,
&Form_Principal::Form_Principal_FormClosing);
this->Load += gcnew System::EventHandler(this,
&Form_Principal::Form_Principal_Load);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
Void Actualizar()
{
array<Byte>^mBuffer = Encoding::ASCII-
>GetBytes("ACTUALIZAR"); // Enva comando ACTUALIZAR por el puerto.
serialPort1->Write(mBuffer, 0, mBuffer->Length);
}
Ejemplo 3:
Se trata en este caso unir los dos ejemplos de Visual Studio, las imgenes de los Leds y mostrar
mensajes en el richTextBox.
Se recomienda mirar el primer ejemplo para seguir bien la gua o entender el concepto si eres
muy novel.
namespace Entrada_Arduino_CPP_CLR_3 {
/// <summary>
/// Resumen de Form_Principal
/// </summary>
public ref class Form_Principal : public Form
{
public:
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();
{
// Asignar el valor de la trama al richTextBox.
richTextBox1->Text += Recibidos;
Recibidos = "";
}
richTextBox1->Text += " " + DateTime::Now.ToString() + "\r";
}
//
#################################################################################
###############################
protected:
/// <summary>
/// Limpiar los recursos que se estn usando.
/// </summary>
~Form_Principal()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Label^ label_Visual_Cpp_CLR;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::PictureBox^ pictureBox1;
private: System::Windows::Forms::PictureBox^ pictureBox2;
private: System::Windows::Forms::PictureBox^ pictureBox3;
private: System::Windows::Forms::PictureBox^ pictureBox4;
private: System::Windows::Forms::Label^ label_Led_1;
private:
/// <summary>
/// Variable del diseador necesaria.
/// </summary>
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox1))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox2))->BeginInit();
(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
//
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";
//
// 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);
this->Controls->Add(this->button_Limpiar);
this->Controls->Add(this->richTextBox1);
this->Controls->Add(this->label4);
this->Controls->Add(this->label3);
this->Controls->Add(this->label2);
this->Controls->Add(this->label_Led_1);
this->Controls->Add(this->pictureBox4);
this->Controls->Add(this->pictureBox3);
this->Controls->Add(this->pictureBox2);
this->Controls->Add(this->pictureBox1);
this->Controls->Add(this->label1);
this->Controls->Add(this->label_Visual_Cpp_CLR);
this->Name = L"Form_Principal";
this->StartPosition =
System::Windows::Forms::FormStartPosition::CenterScreen;
this->Text = L"Electrnica PIC - C++ CLR";
this->FormClosing += gcnew
System::Windows::Forms::FormClosingEventHandler(this,
&Form_Principal::Form_Principal_FormClosing);
this->Load += gcnew System::EventHandler(this,
&Form_Principal::Form_Principal_Load);
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox1))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox2))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox3))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this-
>pictureBox4))->EndInit();
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
Void Actualizar()
{
array<Byte>^mBuffer = Encoding::ASCII-
>GetBytes("ACTUALIZAR"); // Enva comando ACTUALIZAR por el puerto.
serialPort1->Write(mBuffer, 0, mBuffer->Length);
}
}
private: System::Void Form_Principal_Load(System::Object^ sender,
System::EventArgs^ e) {
Actualizar();
}
};
}
Vdeos
Una muestra de un vdeo en este caso con Visual C# 2015 que enciende y apaga un Led. Vale
para los dems lenguajes.
Ttulo:
Encender y Apagar un Led Con Arduino y Visual Studio 2015 / Turn on and off an LED with
Arduino
Enlace:
https://www.youtube.com/watch?v=F6P0ZOceTko
Enlace:
https://www.youtube.com/watch?v=YJ4bjwFSH6o
Enlaces
Descarga ejemplos de este tutorial:
Enlace 1.
Enlace 2.
Arduino:
https://www.arduino.cc/
https://www.visualstudio.com/es-es/products/visual-studio-community-vs.aspx
https://www.visualstudio.com/es-es/products/visual-studio-express-vs.aspx
Foro MSDN:
https://social.msdn.microsoft.com/Forums/es-es/home
Foro TechNET:
https://social.technet.microsoft.com/Forums/es-es/home
Autor
Electrnica PIC
http://electronica-pic.blogspot.com.es