Anterior mente me había estado quebrando la cabeza en hacer la comunicación de mi arduino ethernet shield con android y por un tiempo lo deje pendiende, pero hace hace poco decidí retomarlo y lograr hacer la comunicación teniendo exito
Error
Antes de poner el código y meterle mas rollo, mi problema estaba cuando mandaba los datos, ya que mi código en android cumplía con su función de mandar y mi código de arduino cumplía su función de recibir, ya que al momento de la interacción, el foquito del arduino que indica que recibió un paquete, parpadeaba, entonces ¿Cuál es el problema o error? El error estaba en que mi código de android lo que hacía era postear la variable (algo asi para mandar parametros en un formulario) y mi código de arduino interpretaría los valores recibidos por la url y no por un ¡POST..!!
Código:
No les pondré todo el código la idea es que les ponga las cosas importantes, pero como quiera más abajo pondre el código completo por si lo quieren descargar, ya que si algunos tuvieron el mismo problema se puedan basar en el.
Código de android:
Pondre solo dos métodos los cuales hacen es mandar una señal para que se preda o apague un led, pero en el código completo lo que hace es mandar prender/apagar un led o mover a la izquierda/derecha un servomotor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Prendemos LED | |
public void sendOn(View v){ | |
HttpClient httpclient = new DefaultHttpClient(); | |
HttpPost httppost = new HttpPost("http://192.168.0.110/?L=1"); | |
//Esta es nuestra url donde mandaremos el parametro uno | |
try { | |
//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); | |
//Codigo anterior donde tenia el error, pero esto funciona si queremos hacer post | |
//nameValuePairs.add(new BasicNameValuePair("L", "1")); | |
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); | |
httpclient.execute(httppost); // mandamos el parametro al sercidor | |
} catch (ClientProtocolException e) { | |
// TODO Auto-generated catch block | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
} | |
} | |
//Apagamos LED | |
public void sendOff(View v){ | |
HttpClient httpclient = new DefaultHttpClient(); | |
HttpPost httppost = new HttpPost("http://192.168.0.110/?"); | |
//URL donde lo apagamos ya que no envia ninguna variable, nosotros podriamos ponerle un 0 | |
pero en el codigo del arduino hay que cambiarlo | |
try { | |
//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); | |
//nameValuePairs.add(new BasicNameValuePair("L", "1")); | |
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); | |
httpclient.execute(httppost); | |
} catch (ClientProtocolException e) { | |
// TODO Auto-generated catch block | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
} | |
} |
La url donde mando los datos es 192.168.0.110, ya que esta fue donde cargue la dirección ip del arduino.
Código del arduino:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SPI.h> | |
#include <Ethernet.h> | |
#include <Servo.h> | |
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address | |
byte ip[] = { 192, 168, 0, 110 }; // ip in lan | |
byte gateway[] = { 192, 168, 0, 1 }; // internet access via router | |
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask | |
Server server(80); //server port | |
byte sampledata=50; //some sample data - outputs 2 (ascii = 50 DEC) | |
int ledPin = 2; // LED pin | |
String readString = String(30); //string for fetching data from address | |
boolean LEDON = false; //LED status flag | |
Servo myservo; | |
int pos = 90; | |
void setup(){ | |
//start Ethernet | |
Ethernet.begin(mac, ip, gateway, subnet); | |
//Set pin 4 to output | |
pinMode(ledPin, OUTPUT); | |
//enable serial datada print | |
Serial.begin(9600); | |
myservo.attach(5); | |
myservo.write(pos); | |
} | |
void loop(){ | |
// Create a client connection | |
Client client = server.available(); | |
if (client) { | |
while (client.connected()) { | |
if (client.available()) { | |
char c = client.read(); | |
//read char by char HTTP request | |
if (readString.length() < 100) | |
{ | |
//store characters to string | |
readString += c; //replaces readString.append(c); | |
} | |
//output chars to serial port | |
Serial.print(c); | |
//if HTTP request has ended | |
if (c == '\n') { | |
if (readString.indexOf("?") <0) | |
{ | |
//skip everything | |
} | |
else | |
if(readString.indexOf("L=1") >0) | |
{ | |
digitalWrite(ledPin, HIGH); // set the LED on | |
LEDON = true; | |
}else{ | |
digitalWrite(ledPin, LOW); // set the LED OFF | |
LEDON = false; | |
} | |
if(readString.indexOf("S=1") >0) | |
{ | |
if( pos > 0) | |
pos = 10; | |
myservo.write(pos); | |
} | |
if(readString.indexOf("S=0") >0){ | |
if( pos < 180) | |
pos = 170; | |
myservo.write(pos); | |
} | |
// now output HTML data starting with standart header | |
client.println("HTTP/1.1 200 OK"); | |
client.println("Content-Type: text/html"); | |
client.println(); | |
client.print("<body>"); | |
client.println("<h1>LED control</h1>"); | |
if (LEDON) | |
client.println("<form method=get name=LED><input type=checkbox name=L value=1 CHECKED>LED<br><input type=submit value=submit></form>"); | |
else | |
client.println("<form method=get name=LED><input type=checkbox name=L value=1>LED<br><input type=submit value=submit></form>"); | |
client.println("<br />"); | |
client.println("<form method=get name=SERVO><button name=S value=1>IZQUIERDA</button>"); | |
client.println("<br/><br/>"); | |
client.println("<button name=S value=0>DERECHA</button></form>"); | |
client.println("</body></html>"); | |
readString=""; | |
client.stop(); | |
} | |
} | |
} | |
} | |
} |
Parte de este código me base de uno ya hecho, y tiene comentado, sino tengo una entrada anterior, donde lo explico. Como quiera la parte importante es cuando lee el valor recibido.
Video:
Descargar:
Aquí les dejo la url para que descargen todo el código de android y de arduino
Bibliografía:
http://luisfuentesr.blogspot.mx/2012/02/arduino-ethernet-shield.htmlhttp://arbolesypisosverdes.blogspot.mx/2011/11/arduino-ethernet-shield-led-rgb.html
http://arduinoprojectsfiuady.blogspot.mx/2012/02/controlar-via-telnet-un-arduino.html
Gracias, me miraré tu código, será una buena basé para lo que quiero
ResponderEliminarexcelente aporte!!!!
ResponderEliminarme podria ayudar con el link de descarga ...existe problemas con el link..gracias
ResponderEliminarSu ayuda mi estimado con el link de descarga ya que me gustaria aprender a integrar esas dos tecnologias
ResponderEliminarEste comentario ha sido eliminado por el autor.
ResponderEliminar