You are on page 1of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

Arduino y Visual Basic


por Juan Antonio Villalpando
mi correo: juana1991@yahoo.com)
(IES Fco. Romero Vargas - Jerez de la Fra.)
Los programas utilizados estn basados en los encontrados en las siguentes web:
http://www.instructables.com/id/Using-Visual-Basic-to-control-Arduino-Uno/
http://stackoverflow.com/questions/5697047/convert-serial-read-into-a-useable-string-using-arduino
http://arduino.cc/forum/index.php?action=printpage;topic=65486.0
http://msdn.microsoft.com/es-es/library/7ya7y41k.aspx
----------------------------------------------------------------------------------

Visual Basic 2010 lo puedes bajar de... http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-basic-express


****************************************************************************************************************************************************************

Conexionado
Monta este conexionado para realizar la mayora de los programas de este tutorial

http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 1 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

NOTA: Cuando tenemos abierto el puerto COM3 no podemos utilizar a la vez el Serial Monitor.
NOTA: Con un Hyperterminal tambin podemos comunicarnos con el Arduino.

1.- Se trata de gobernar el Arduino desde Visual


Basic 2010.
Creamos dos botones, cuando pulsamos estos
botones se apaga o enciende el LED13 del
Arduino.
En Visual Basic 2010, insertamos dos Botones y un SerialPort
http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 2 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

- Cambia el puerto COM3 por el puerto que tengas en el Arduino (1, 2, 3 o 4)


Cuando pulsamos el Button1 se enciende el LED13
Cuando pulsamos el Button2 se apaga el LED13

Visual Basic 2010

Imports System.IO
Imports System.IO.Ports
Imports System.Threading
Public Class Form1
Shared _continue As Boolean
Shared _serialPort As SerialPort
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SerialPort1.Close()
SerialPort1.PortName = "com3" ' Cambia el Puerto
SerialPort1.BaudRate = 9600
SerialPort1.DataBits = 8
SerialPort1.Parity = Parity.None
SerialPort1.StopBits = StopBits.One
SerialPort1.Handshake = Handshake.None
SerialPort1.Encoding = System.Text.Encoding.Default
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SerialPort1.Open()
SerialPort1.Write("1")
SerialPort1.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SerialPort1.Open()
SerialPort1.Write("0")
SerialPort1.Close()
End Sub
End Class

En el Arduino creamos este cdigo.

Programa para el Arduino

int ledPin = 13;


void setup() {
Serial.begin(9600);
http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 3 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
}
void loop(){
while (Serial.available() == 0);
int val = Serial.read() - '0';
if (val == 1) {
Serial.println("LED on");
digitalWrite(ledPin, HIGH);
}
else if (val == 0)
{
Serial.println("LED OFF");
digitalWrite(ledPin, LOW);
}
else
{
//val = val;
}
Serial.println(val);
Serial.flush();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

2.- Ahora con dos botones y dos LED


Ahora se trata de tener varios Botones para controlar varios LED
Cuando pulsamos el Botn 1, se enciende el LED13, cuando volvemos a pulsarlo se apaga el LED13
Cuando pulsamos el Botn 2, se enciende el LED12, cuando volvemos a pulsarlo se apaga el LED12

Visual Basic 2010

Imports System.IO.Ports
Imports System.Threading
Public Class Form1
Dim cambio12 As Boolean = True
Dim cambio13 As Boolean = True
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SerialPort1.Close()
SerialPort1.PortName = "com3" 'CAMBIA EL PUERTO COM
SerialPort1.BaudRate = 9600
SerialPort1.DataBits = 8
SerialPort1.Parity = Parity.None
SerialPort1.StopBits = StopBits.One
http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 4 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

SerialPort1.Handshake = Handshake.None
SerialPort1.Encoding = System.Text.Encoding.Default
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SerialPort1.Open()
If cambio13 = True Then
SerialPort1.Write("13 on")
Else
SerialPort1.Write("13 off")
End If
cambio13 = Not (cambio13)
SerialPort1.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SerialPort1.Open()
If cambio12 = True Then
SerialPort1.Write("12 on")
Else
SerialPort1.Write("12 off")
End If
cambio12 = Not (cambio12)
SerialPort1.Close()
End Sub
End Class

En el Arduino creamos este cdigo.

Programa para el Arduino


char inData[20]; // Allocate some space for the string
char inChar=-1; // Where to store the character read
byte index = 0; // Index into array; where to store the character
void setup() {
Serial.begin(9600);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
}
char Comp(char* This) {
while (Serial.available() > 0) // Don't read unless
// there you know there is data
{
if(index < 19) // One less than the size of the array
{
inChar = Serial.read(); // Read a character
inData[index] = inChar; // Store it
index++; // Increment where to write next
inData[index] = '\0'; // Null terminate the string
}
}
if (strcmp(inData,This) == 0) {
for (int i=0;i<19;i++) {
inData[i]=0;
}
index=0;
return(0);
}
else {
return(1);
}
}
void loop()
{
if (Comp("12 on")==0) { digitalWrite(12, HIGH);}
if (Comp("12 off")==0) {digitalWrite(12, LOW);}
if (Comp("13 on")==0) { digitalWrite(13, HIGH);}
if (Comp("13 off")==0) {digitalWrite(13, LOW);}
http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 5 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

Lo que hace el programa Visual Basic anterior es enviar la frase "12 on" al puerto serie (En este caso no es el puerto serie, se trata del USB), el Arduino recoje
la informacin que le llega por su puerto serie y "descompone" las letras recibidas, si las letras "descompuestas" son 12 on, entonces se enciende el LED 12.
- Ahora lo mismo pero con otro cdigo ms sencillo, dos botones y dos LED. En este caso solo se enva un carcter ("1"), no una cadena "12 on")

Visual Basic - Arduino


' VISUAL BASIC 2010 (dos Button y un SerialPort)
' Programa realizado por Juan Antonio Villalpando
' juana1991@yahoo.com
Imports System.IO.Ports
Imports System.Threading
Public Class Form1
Dim cambio12 As Boolean = True
Dim cambio13 As Boolean = True
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SerialPort1.Close()
SerialPort1.PortName = "com3" 'CAMBIA EL PUERTO COM
SerialPort1.BaudRate = 9600
SerialPort1.DataBits = 8
SerialPort1.Parity = Parity.None
SerialPort1.StopBits = StopBits.One
SerialPort1.Handshake = Handshake.None
SerialPort1.Encoding = System.Text.Encoding.Default
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SerialPort1.Open()
If cambio13 = True Then
SerialPort1.Write("1")
Else
SerialPort1.Write("2")
End If
cambio13 = Not (cambio13)
SerialPort1.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SerialPort1.Open()
If cambio12 = True Then
SerialPort1.Write("3")
Else
SerialPort1.Write("4")
End If
cambio12 = Not (cambio12)
SerialPort1.Close()
End Sub
End Class
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
/////////////////////////////////////////////////////////////////////////////////////////////////
/ ARDUINO
// Programa realizado por Juan Antonio Villalpando
// juana1991@yahoo.com
int ledPin13 = 13;
int ledPin12 = 12;
int dato;
void setup() {
Serial.begin(9600);
pinMode(ledPin13, OUTPUT);
pinMode(ledPin12, OUTPUT);
}

http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 6 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

void loop() {
if (Serial.available() > 0) {
dato = Serial.read();
if (dato == '1') {
digitalWrite(ledPin13, HIGH);
}
if (dato == '2') {
digitalWrite(ledPin13, LOW);
}
if (dato == '3') {
digitalWrite(ledPin12, HIGH);
}
if (dato == '4') {
digitalWrite(ledPin12, LOW);
}
}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

3.- Ahora lo hacemos alrevs, es decir, pulsamos


un botn en el Arduino y enviamos un mensaje a
Visual Basic 2010
1.- Para hacerlo funcionar, primero pulsamos el Botn "Abrir puerto" para abrir el puerto COM3
2.- Luego pulsamos el botn de Recibir y quedamos a la espera.
3.- Cuando pulsemos el Botn del Arduino, pasar la informacin "Hola amigo" al Visual Basic y lo presentar en el Label1.
4. Para acabar el programa debemos pulsar el botn de "Cerrar puerto", si no lo cerramos el puerto quedar bloqueado y no podremos volver a cargar el
Arduino.
En este caso, ejecuta el programa de Visual Basic y pulsa el botn de "Cerrar puerto"
- El botn "Enviar" no tiene cdigo, cuando lo pulsemos el Arduino notar que le llega algo por el puerto serie mediante el LED TX.

Visual Basic 2010


Insertamos 4 botones, 1 Label y un TextBox. Tambin insertamos un SerialPort y en su Propiedad PortName, establecemos el Puerto de
conexin del Arduino.

Public Class Form1

http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 7 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

Private Sub Form1_Disposed(ByVal sender As Object, ByVal e As System.EventArgs)


SerialPort1.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SerialPort1.Open()
Button1.Enabled = False
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SerialPort1.Close()
Button1.Enabled = True
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Label1.Text = SerialPort1.ReadLine
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
SerialPort1.WriteLine(TextBox1.Text)
End Sub
End Class
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

' Para que se abra el Bloc de notas cuando se pulse el botn del Arduino y se reciba la palabra Hola
Dim a As String
.........................................
a = SerialPort1.ReadLine
If a = "Hola amigo" & vbCr & "" Then System.Diagnostics.Process.Start("notepad.exe")
********************************************************************************
' Mejora del cdigo. Dos botones y un SerialPort. No hace falta el botn Recibir ni Enviar.

Public Class Form1


Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
SerialPort1.Close()
SerialPort1.PortName = "com3" ' Cambia el Puerto
SerialPort1.BaudRate = 9600 ' Esta es la velocidad de transmisin, debe ser la misma en los programas y en el Bluetooth
CheckForIllegalCrossThreadCalls = False ' Esta lnea no le gusta mucho a los programadores, pero aqu la ponemos para que funcione el Label1
End Sub
Private Sub Form1_Disposed(ByVal sender As Object, ByVal e As System.EventArgs)
SerialPort1.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SerialPort1.Open()
Button1.Enabled = False
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SerialPort1.Close()
Button1.Enabled = True
Label1.Text =""
End Sub
Private Sub SerialPort1_DataReceived(sender As Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Label1.Text = Label1.Text & SerialPort1.ReadLine
If SerialPort1.ReadLine = "Hola amigo" & vbCr & "" Then Process.Start("calc.exe")
End Sub
End Class

En el Arduino creamos este cdigo.

http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 8 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

Programa para el Arduino


const int boton2 = 2;
const int ledPin = 13;
int buttonState = 0;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(boton2, INPUT);
}
void loop(){
buttonState = digitalRead(boton2);
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH);
Serial.println("Hola amigo");
}
else {
digitalWrite(ledPin, LOW);
}
}

********************************************************************************************************************

4.- Ahora se trata de realizar un programa que


pueda enviar datos al Arduino y recibirlo. Se
basa en unir los dos programas vistos
anteriormente.
1.- Este programa est formado por los dos programas vistos anteriormente.

http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 9 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

Visual Basic 2010


Insertamos 4 botones, 1 Label y un TextBox. Tambin insertamos un SerialPort y en su Propiedad PortName, establecemos el Puerto de
conexin del Arduino.

Imports System.IO
Imports System.IO.Ports
Imports System.Threading
' Programa realizado por Juan Antonio Villalpando
' juana1991@yahoo.com
' Este programa trata de dos modalidades distintas
' una pulsamos un botn en Visual Basic y se enciende un LED en el Arduino
' otra pulsamos un botn en el Arduino y se envia un mensaje al Visual Basic y se ejecuta un programa.
Public Class Form1
Private Sub Form1_Disposed(ByVal sender As Object, ByVal e As System.EventArgs)
SerialPort1.Close()
End Sub
Shared _continue As Boolean
Shared _serialPort As SerialPort
Dim cambio12 As Boolean = True
Dim cambio13 As Boolean = True
Dim entradadedatos As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SerialPort1.Close()
SerialPort1.PortName = "com3" 'CAMBIA EL PUERTO COM
SerialPort1.BaudRate = 9600
SerialPort1.DataBits = 8
SerialPort1.Parity = Parity.None
http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 10 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

SerialPort1.StopBits = StopBits.One
SerialPort1.Handshake = Handshake.None
SerialPort1.Encoding = System.Text.Encoding.Default
End Sub
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' SALIDA DE DATOS
' Enciende / Apaga LED12 y LED13
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SerialPort1.Close()
SerialPort1.Open()
If cambio13 = True Then
SerialPort1.Write("13 on")
Else
SerialPort1.Write("13 off")
End If
cambio13 = Not (cambio13)
SerialPort1.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SerialPort1.Close()
SerialPort1.Open()
If cambio12 = True Then
SerialPort1.Write("12 on")
Else
SerialPort1.Write("12 off")
End If
cambio12 = Not (cambio12)
SerialPort1.Close()
End Sub
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ENTRADA DE DATOS
' Botones del Arduino
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
SerialPort1.Close()
SerialPort1.Open()
Button3.Enabled = False
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
SerialPort1.Close()
Button3.Enabled = True
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Button5.BackColor = Color.GreenYellow
Button5.Text = "Pulsa un botn del Arduino"
SerialPort1.Close()
SerialPort1.Open()
entradadedatos = SerialPort1.ReadLine
Label1.Text = entradadedatos
If entradadedatos = "Bloc de notas" & vbCr & "" Then System.Diagnostics.Process.Start("notepad.exe")
If entradadedatos = "Calculadora" & vbCr & "" Then System.Diagnostics.Process.Start("calc.exe")
SerialPort1.Close()
' Button5.BackColor = SystemColors.Control
Button5.BackColor = Color.OrangeRed
Button5.Text = "Preparado para recibir"
End Sub
End Class

En el Arduino creamos este cdigo.

Programa para el Arduino

char inData[20]; // Allocate some space for the string


char inChar=-1; // Where to store the character read

http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 11 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

byte index = 0; // Index into array; where to store the character


// Programa adaptado por Juan Antonio Villalpando
int boton2 = 0;
int boton3 = 0;
void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
pinMode(3, INPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
}
// ENCENDIDO DEL LED12 y LED13
////////////////////////////////////////////////////////////////
char Comp(char* This) {
while (Serial.available() > 0)
{
if(index < 19) // One less than the size of the array
{
inChar = Serial.read(); // Read a character
inData[index] = inChar; // Store it
index++; // Increment where to write next
inData[index] = '\0'; // Null terminate the string
}
}
if (strcmp(inData,This) == 0) {
for (int i=0;i<19;i++) {
inData[i]=0;
}
index=0;
return(0);
}
else {
return(1);
}
}
void loop()
{
if (Comp("12 on")==0) { digitalWrite(12, HIGH);}
if (Comp("12 off")==0) {digitalWrite(12, LOW);}
if (Comp("13 on")==0) { digitalWrite(13, HIGH);}
if (Comp("13 off")==0) {digitalWrite(13, LOW);}
// LECTURA DE LOS BOTONES 2 y 3 DEL ARDUINO
///////////////////////////////////////////////////////////////////////////////////////////
// Lee el estado de los botones
boton2 = digitalRead(2);
boton3 = digitalRead(3);
if (boton2 == HIGH) {
Serial.println("Bloc de notas");
// digitalWrite(12, HIGH);
delay(300);
}
else {
//
//digitalWrite(12, LOW);
}
if (boton3 == HIGH) {
Serial.println("Calculadora");
// digitalWrite(13, HIGH);
delay(300);
}
else {
//
// digitalWrite(13, LOW);
}
}

http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 12 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

*************************************************************************************************************

Servidor Apache + PHP


Para realizar los programas basados en PHP en nuestro ordenador, debemos instalar un servidor web, es muy fcil.
1.- Instalamos el WAMP (Windows Apache MySQL PHP)
2.- Se instala en C:\wamp. La carpeta donde tienes que poner los php es C:\wamp\www.
3.- La configuracin se realiza con una ventana que sale en el rea de notificacin cerca del reloj.
4.- El archivo de configuracin es el httpd.conf en este archivo ponemos una almohadilla en...
# onlineoffline tag - don't remove
Order Allow,Deny
# Deny from all
Allow from all
5.- Cada vez que guardemos el archivo de configuracin debemos Restart el servicio Apache.
6.- Para ver los php, ponemos en un navegador: localhost/arduino.php

5.- Se trata de realizar un programa que pueda


enviar datos al Arduino mediante un archivo PHP
alojado en un servidor web.
1.- Creamos un archivo arduino.php con cuatro botones.
2.- Dependiendo del botn pulsado se enviar al puerto serie un carcter chr(48), chr(49), chr(50), chr(51) que corresponde al "0", "1", "2" y "3"
3.- El Arduino leer el dato del puerto serie y segn sea "0", "1", "2" o "3" mandar seal a las salidas 12 y 13 y los LED encencern o apagarn.
http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 13 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

.
Es posible que el archivo arduino2.php de un error cuando se ejecuta por primera vez, ignorarlo.

arduino.php
// Programa realizado por Juan Antonio Villalpando
// juana1991@yahoo.com
<?php
//`mode com3: BAUD=9600 PARITY=N data=8 stop=1 xon=off`;
$fp = fopen ("COM3:", "a");
?>
<html>
<head>
<Form Name ="form1" Method ="POST" ACTION = "arduino.php">
<INPUT TYPE = "Submit" Name = "dato" VALUE = "13 on">
<INPUT TYPE = "Submit" Name = "dato" VALUE = "13 off">
<INPUT TYPE = "Submit" Name = "dato" VALUE = "12 on">
<INPUT TYPE = "Submit" Name = "dato" VALUE = "12 off">
</html>
<?php
$datos=$_POST;
$dato = $datos['dato'];
if ($dato=="13 on") {
echo "Enciende LED 13" ;
fputs($fp, chr(48));
}
if ($dato=="13 off") {
echo "Apaga LED 13" ;
fputs($fp, chr(49));
}
if ($dato=="12 on") {
echo "Enciende LED 12" ;
fputs($fp, chr(50));
}
if ($dato=="12 off") {
echo "Apaga LED 12" ;
fputs($fp, chr(51));
}
?>

En el Arduino creamos este cdigo.

Programa para el Arduino


// Programa realizado por Juan Antonio Villalpando
// juana1991@yahoo.com
int ledPin13 = 13;
int ledPin12 = 12;
int dato;
void setup() {
Serial.begin(9600);
pinMode(ledPin13, OUTPUT);
pinMode(ledPin12, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 14 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

dato = Serial.read();
if (dato == '0') {
digitalWrite(ledPin13, HIGH);
}
if (dato == '1') {
digitalWrite(ledPin13, LOW);
}
if (dato == '2') {
digitalWrite(ledPin12, HIGH);
}
if (dato == '3') {
digitalWrite(ledPin12, LOW);
}
}
}

**********************************************************************************************************************************************.

6.- Vamos a realizar un programa que pueda


enviar datos al Arduino mediante un archivo
PHP, en este caso al apretar un botn se
incrementa el brillo del LED y al apretar otro
botn se decrementa el brillo del LED.
1.- Creamos un archivo arduino2.php con dos botones (Incrementa y Decrementa)
2.- Segn pulsemos uno u otro, se enviar por el puerto serie el chr(48) que es el carcter "0" o el chr(49) que es el carcter "1"
3.- El Arduino leer el dato del puerto serie y segn sea "0" o "1", incrementara o decrementar la variable brillo.
4.- El valor de la variable brillo ir a la salida PWM 9, dependiendo del valor de la variable, dar un nivel de tensin.
Es posible que el archivo arduino2.php de un error cuando se ejecuta por primera vez, ignorarlo.

arduino2.php
// Programa realizado por Juan Antonio Villalpando
// juana1991@yahoo.com
<?php
//`mode com3: BAUD=9600 PARITY=N data=8 stop=1 xon=off`;
$fp = fopen ("COM3:", "a");
?>
<html>
<head>
<Form Name ="form1" Method ="POST" ACTION = "arduino2.php">
<INPUT TYPE = "Submit" Name = "dato" VALUE = "Incrementa">
<INPUT TYPE = "Submit" Name = "dato" VALUE = "Decrementa">
</html>
<?php
$datos=$_POST;
$dato = $datos['dato'];
if ($dato=="Incrementa") {
echo "Incrementa" ;
fputs($fp, chr(48));
}
http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 15 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

if ($dato=="Decrementa") {
echo "Decrementa" ;
fputs($fp, chr(49));
}
?>

En el Arduino creamos este cdigo.


NOTA: en los esquemas anteriores utilizamos las salidas 12 y 13, en este montaje debemos utilizar la salida 9 ya que necesitamos que sea PWM.
Simplemente cambia el cable de la salida 13 de los montajes anteriores por la 9.

Programa para el Arduino


// Programa realizado por Juan Antonio Villalpando
// juana1991@yahoo.com
int ledPin9 = 9;
int dato;
int brillo = 0;
int incremento = 5;
void setup() {
Serial.begin(9600);
pinMode(ledPin9, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
dato = Serial.read();
if (dato == '0') {
analogWrite(ledPin9, brillo);
brillo = brillo + incremento;
}
if (dato == '1') {
analogWrite(ledPin9, brillo);
brillo = brillo - incremento;
}
}
}

*********************************************************************************************************************
*********************************************************************************************************************
*********************************************************************************************************************

7.- Intento de pulsar un botn en el Arduino y


que lo detecte una pgina php.
arduino3.pde
// Programa realizado por Juan Antonio Villalpando
// juana1991@yahoo.com
const int boton2 = 2;
const int ledPin = 13;
int buttonState = 0;

http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 16 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(boton2, INPUT);
}
void loop(){
buttonState = digitalRead(boton2);
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH);
Serial.print("HOLA");
}
else {
digitalWrite(ledPin, LOW);
}
}

arduino3.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="refresh" content="1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<p>Valor leido :</p>
<?php
if ($handle = fopen("COM3", "rb")) {
$data = fread($handle, 8);
print "<center><h1>";
echo $data;
print "</h1></center>";
fclose($handle);
}
?>
</body>
</html>
http://wiki.pinguino.cc/index.php/Interfacing_with_php
**************************************************

Otro intento. Este ha funcionado, aunque no correctamente.


// ini_set ( "max_execution_time" , 99 );
<?php
$fp = fopen ("COM3:", "r+");
if (!$fp) {
echo "Error";
} else {
while (($char = fread($fp,10)) != chr(13)) {
echo $char;
}
fclose ($fp);
}

http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 17 of 19

Arduino y Visual Basic

2013-05-28 1:39 AM

?>

******************************************************************

con .exe freebasic


Mediante un .exe Ver: "http://arduino.cc/forum/index.php?action=printpage;topic=65552.0"
Dim As String qs, dat
Dim idx As Integer
qs = Environ("QUERY_STRING")
if qs = "" goto nodata
again:
idx = Instr(qs, "-")
Mid(qs, idx, 1) = "#"
if idx > 0 goto again
qs = qs
Open Com "COM3: 9600,N,8,1,BIN,CD,CS,DS,RS" For Binary As #1
print #1,, qs
Sleep 200
dat = Input$(loc(1), #1)
Close #1
if dat = "" goto nodata
if dat <> "" goto gotdata
nodata:
Print "status: 204"
Print
Print
goto fini
gotdata:
Print "Content-type: text/html"
Print
print "<html><body>"
Print dat
Print "http://arduino.cc/forum/index.php?action=printpage;topic=65552.0"
Print "</body></html>"
goto fini
fini:
end
*************************
Guardar como arduino.bas y luego compliar f bc .....................arduino.exe y lo guardamos en el directorio cgi-bin del Apache.
Luego en httpd.conf
# ScriptAlias /cgi-bin/ "cgi-bin/"
ScriptAlias /cgi-bin/ "/wamp/bin/apache/Apache2.2.21/cgi-bin/"
#<Directory "cgi-bin">
<Directory "c:/wamp/bin/apache/Apache2.2.21/cgi-bin">
AddHandler cgi-script .cgi .exe .pl

- Otro cdigo en VB parecido a lo anterior. de http://tiktakx.wordpress.com/2010/11/21/serial-port-interfacing-with-vb-net-2010/

http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 18 of 19

Arduino y Visual Basic

2013-05-28 1:40 AM

- Arduino PHP
- Chat Bluetooth -VisualBasic
- http://www.amarino-toolkit.net/index.php/getting-started.html
- http://my.opera.com/gatodrolo/blog/show.dml/20699632
- http://www.instructables.com/id/how-to-Control-arduino-by-bluetooth-from-PC-pock/step6/controlling-from-a-pocket-PC-PDA/
- http://www.electan.com/emisor-receptor-433mhz-p-3039.html
- http://www.electan.com/arduino-mega-adk-android-p-3141.html
- http://www.instructables.com/id/Use-Twitter-to-control-Arduino-Uno-via-Visual-Basi/
- http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1266689999/all recibir datos
- Hyperterminal para conectarse al Arduino. http://www.pcworld.com/downloads/file_download/fid,3376-order,4/download.html
- http://www.mbeckler.org/microcontrollers/rgb_led/

En un prximo tuturial desarrollar la transmisin por Bluetooth, para ello debemos adquirir un Arduino Bluetooth como esta:
http://www.arduino.cc/en/Main/ArduinoBoardBluetooth
(Ver precio: http://www.electan.com/arduino-bluetooth-p-2935.html) - unos 94
o bien comprar un mdulo Bluetooth que se lo podemos insertar a nuestro Arduino bsico: http://www.bricogeek.com/shop/modulos-radiofrecuencia/242modem-bluetooth-bluesmirf-gold.htmlunos 51
(Ver forma de conectar: http://wiring.org.co/learning/tutorials/bluetooth/)
Tambin tengo pendiente hacer un tutorial para transmitir datos por RF, para ello se utiliza un par de mdulo bastante baratos, unos 7 :
http://www.electan.com/emisor-receptor-433mhz-p-3039.html

*******************************************

Lo siguiente ser comunicar el Arduino con el ordenador mediante Bluetooth

1.640.672

http://www.iesromerovargas.net/recursos/elec/sol/arduino.htm

Page 19 of 19

You might also like