Sunteți pe pagina 1din 6

Enviar valores desde PHP/MySQL a Arduino a travs de Internet (SO...

1 de 6

http://forum.arduino.cc/index.php?topic=97264.0;wap2

Enviar valores desde PHP/MySQL a Arduino a travs de Internet (SOLUCIONADO)


(1/1)
Hallenbeck:
Hola,
Llevo unos das liado con este problema, a ver si me podis echar un mano.
Para empezar tengo esta configuracin:
-Arduino Mega(1280). IDE 1.0
-Ethernet Shield w5100.
-Sensores de temperatura DS18B20 y un par de LDRs.
-Servidor Apache funcionando correctamente con PHP y MySQL sobre Windows 7 x64.
Tengo un cdigo (la idea es hacer una aplicacin domtica a travs de Internet, con interfaz Web) funcionando que manda los valores de los sensores a travs de
un script php que a su vez se comunica con la base de datos, aadiendo correctamente los valores.
Hasta ah perfecto, luego los muestro en una pgina web alojada en el mismo servidor Apache y voy actualizando los valores mediante otros scripts php que hacen
consultas a la base de datos.
Ahora necesito mandar de vuelta al Arduino algunos valores para, por ejemplo, encender una luz, activar un rel...
Me da igual que sea por PHP directamente, pasando por la web...
Se os ocurre alguna forma de hacerlo? He estado mirando por este foro y por Internet y he encontrado algo similar, pero por el puerto serie, conectando el
Arduino al ordenador que tiene alojado el servidor Apache. La idea es hacerlo independiente de ordenadores.
Aqu los cdigos:
Arduino:
Code:
#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <SPI.h>
#include <Ethernet.h>
//*****************************************SENSOR TEMPERATURA DS18B20*****************************************//
#define ONE_WIRE_BUS 4
//the onewire bus is connected to pin 4 on arduino
#define TEMPERATURE_PRECISION 10 //resolution of the sensors is set to 10bit(somehow wont work)
OneWire oneWire(ONE_WIRE_BUS);
// setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
DallasTemperature sensors(&oneWire);
// Pass our oneWire reference to Dallas Temperature

//*****************************************ETHERNET*****************************************//
byte mac[] = {
0x00, 0x11, 0x22, 0x33, 0xFB, 0x11 }; // Mac del dispositivo ethernet
byte ip[] = {
192, 168, 1, 18 };
// ip del dispositivo ethernet
//byte miServidor[] = { 192, 168, 1, 15 };
byte miServidor[]= {
192,168,1,10};
// ip del servidor web donde esta alojada la pagina
EthernetClient client;

int pinLDR=0;
int valorLDR;
int pinLDRext=1;
int valorLDRext;

//LDR conectado a ANALOGICO 0

//LDR conectado a ANALOGICO 1

boolean luzEncendida=false;

void setup(){
Wire.begin();
Serial.begin(9600);
pinMode(pinLDR,INPUT);
sensors.begin();
// start up the library for the DS18B20
int numSensors = sensors.getDeviceCount();
// store the number of sensors to the variable numSensors,
float temparray[numSensors];
// array with "numSensors" storage places for the temperature of each sensor
// "sensors.getDeviceCount" is a function in the library

28/08/2014 14:38

Enviar valores desde PHP/MySQL a Arduino a travs de Internet (SO...

2 de 6

http://forum.arduino.cc/index.php?topic=97264.0;wap2

if(numSensors > 0)
// if there is at least one sensor:
{
Serial.print("Numero de sensores: ");
//print the number of sensors to serial port
Serial.print(numSensors);
}
else
//if there is no sensor:
{
Serial.println("No sensors enumerated."); // tell the serial port
}
}
void loop(){
Serial.print("Luminosidad dentro: ");
valorLDR=analogRead(pinLDR);
//lectura del valor LDR
Serial.print(valorLDR);
if(valorLDR <10){
//diferentes rangos de luz
Serial.println(" - Muy oscuro");
}
else if(valorLDR <200){
Serial.println(" - Oscuro");
}
else if(valorLDR <500){
Serial.println(" - Tenue");
}
else if(valorLDR <800){
Serial.println(" - Brillante");
}
else{
Serial.println(" - Muy brillante");
}
Serial.print("Luminosidad fuera: ");
valorLDRext=analogRead(pinLDRext);
//lectura del valor LDR
Serial.print(valorLDRext);
if(valorLDRext <10){
//diferentes rangos de luz
Serial.println(" - Muy oscuro");
}
else if(valorLDRext <200){
Serial.println(" - Oscuro");
}
else if(valorLDRext <500){
Serial.println(" - Tenue");
}
else if(valorLDRext <800){
Serial.println(" - Brillante");
}
else{
Serial.println(" - Muy brillante");
}

int numSensors = sensors.getDeviceCount();


float temparray[numSensors];
// array with "numSensors" storage places for the temperature of each sensor
// "sensors.getDeviceCount" is a function in the dallas temperature library
sensors.requestTemperatures();
// send the request for temperature to sensors (all sensors)
delay(100);
for(int i=0; i<numSensors; i++)
// as long as "i" ( chosen number, starts at 0) is smaller than
//numSensors" (number of sensors) do the "for" cycle
{
float temp = sensors.getTempCByIndex(i); // take temperature reading from sensor "i" and store it to the variable "temp"
Serial.println(temp);
temparray[i] = temp;
// store the temperature from sensor i to storage place i in the array
}
Serial.println();
senddata(numSensors,temparray);
Serial.print("\n\n\n\n\n");
delay(1000);
}

//*****************************************FUNCION PARA CONEXION PHP Y MANDAR


DATOS*****************************************//
void senddata(int numSensors, float temparray[])
{

28/08/2014 14:38

Enviar valores desde PHP/MySQL a Arduino a travs de Internet (SO...

3 de 6

http://forum.arduino.cc/index.php?topic=97264.0;wap2

Ethernet.begin(mac, ip);
EthernetClient client;
Serial.println();
Serial.println("Inicializando Conexion");
Serial.println("Conectando");
delay(1000); //This one keeps it from hanging, anteriormente 1000
if (client.connect(miServidor,80)) {
Serial.println("Conectado");
client.print("GET http://192.168.1.10/PHPFile.php?");
Serial.print("GET http://192.168.1.10/PHPFile.php?");
for (int i=0; i<numSensors; i++){ //va metiendo las variables t0, t1... segun el numero de sensores
client.print("t");
Serial.print("t");
client.print(i);
Serial.print(i);
client.print("=");
Serial.print("=");
client.print(temparray[i]);
Serial.print(temparray[i]);
if (i < numSensors-1){
client.print("&");
Serial.print("&");
}
else{
}
}
client.print("&luzInterna=");
Serial.print("&luzInterna=");
client.print(valorLDR);
Serial.print(valorLDR);
client.print("&esBooleano=");
Serial.print("&esBooleano=");
if (luzEncendida){
client.print(1);
Serial.print(1);
}
else{
client.print(0);
Serial.print(0);
}
client.print("&luzExterna=");
Serial.print("&luzExterna=");
client.print(valorLDRext);
Serial.print(valorLDRext);
client.println(" HTTP/1.1");
Serial.println(" HTTP/1.1");
client.println("Host: http://192.168.1.10");
Serial.println("Host: http://192.168.1.10");
client.println();
}
else
{
Serial.println("Connection failed");
}
//}
//stop client
client.stop();
while(client.status() != 0)
{
delay(5);
}
}

Cdigo PHP:
(por si se puede adaptar para que se manden las variables al Arduino)
Code:
<html>
<?php
$t0 = $_GET['t0'];
$t1= $_GET['t1'];
$luzInterna=$_GET['luzInterna'];
$Encendido=$_GET['esBooleano'];
$luzExterna=$_GET[luzExterna];

28/08/2014 14:38

Enviar valores desde PHP/MySQL a Arduino a travs de Internet (SO...

4 de 6

http://forum.arduino.cc/index.php?topic=97264.0;wap2

//Connect to database
$opendb = mysql_connect("192.168.1.10", "usuario", "pass") or mysql_error("Error");
mysql_select_db("domos");
if ($opendb){
mysql_query("INSERT INTO mytable (Fecha,t0, t1, luzInterna, Encendido, luzExterna) VALUES ( NOW(), $t0 , $t1, $luzInterna, $Encendido,$luzExterna)");
mysql_close($opendb);
}
?>
</html>
Gracias, un saludo.

Sergegsx:
q te parece llamar a un php con un parametro que sea indique el dato que deseas.
el php reconoce el parametro, hace la consulta mysql e imprime con un echo el resultado.
el arduino lee lo que devuelve y actua.
Hallenbeck:
Lo probar, a ver si saco algo maana.
Gracias por la respuesta!
Hallenbeck:
He llegado a una solucin y parece que funciona, por lo menos hace lo que yo quiero.
Me he basado en este ejemplo: http://bildr.org/2011/06/arduino-ethernet-client/

Code:
#include <Ethernet.h>
#include <SPI.h>
////////////////////////////////////////////////////////////////////////
//CONFIGURE
////////////////////////////////////////////////////////////////////////
byte server[] = { 192,168,1,10 }; //ip Address of the server you will connect to

String location = "http://192.168.1.10/cargaDatosEnArduino.php HTTP/1.0";

// if need to change the MAC address (Very Rare)


byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
////////////////////////////////////////////////////////////////////////
EthernetClient client;
char inString[32]; // string for incoming serial data
int stringPos = 0; // string index counter
boolean startRead = false; // is reading?
void setup(){
Ethernet.begin(mac);
Serial.begin(9600);
}
void loop(){
String pageValue = connectAndRead(); //connect to the server and read the output
Serial.println(pageValue); //print out the findings.
delay(3000); //wait 3 seconds before connecting again
}
String connectAndRead(){
//connect to the server
Serial.println("connecting...");
//port 80 is typical of a www page
if (client.connect(server, 80)) {
Serial.println("connected");
client.print("GET ");

28/08/2014 14:38

Enviar valores desde PHP/MySQL a Arduino a travs de Internet (SO...

5 de 6

http://forum.arduino.cc/index.php?topic=97264.0;wap2

client.println(location);
client.println();
//Connected - Read the page
return readPage(); //go and read the output
}else{
return "connection failed";
}
}
String readPage(){
//read the page, and capture & return everything between '<' and '>'
stringPos = 0;
memset( &inString, 0, 32 ); //clear inString memory
while(true){
if (client.available()) {
char c = client.read();
if (c == '<' ) { //'<' is our begining character
startRead = true; //Ready to start reading the part
}else if(startRead){
if(c != '>'){ //'>' is our ending character
inString[stringPos] = c;
stringPos ++;
}else{
//got what we need here! We can disconnect now
startRead = false;
client.stop();
client.flush();
Serial.println("disconnecting.");
return inString;
}
}
}
}
}
Este cdigo espera recibir una serie de datos encerrados por < y >.
El cdigo php es el siguiente:
Code:
<?php
$username="usuario";
$password="pass";
$database="domo";
mysql_connect("192.168.1.10",$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM actuadores";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$i=0;
$LuzPrincipal=mysql_result($result,$i,"LuzPrincipal");
$LuzMesa=mysql_result($result,$i,"LuzMesa");
$Persiana=mysql_result($result,$i,"Persiana");
$Store=mysql_result($result,$i,"Store");
$Clima=mysql_result($result,$i,"Clima");
$Ventilacion=mysql_result($result,$i,"Ventilacion");
echo '<'.",".$LuzPrincipal.",".$LuzMesa.",".$Persiana.",".$Store.",".$Clima.",".$Ventilacion.'>'
?>

28/08/2014 14:38

Enviar valores desde PHP/MySQL a Arduino a travs de Internet (SO...

6 de 6

http://forum.arduino.cc/index.php?topic=97264.0;wap2

Primero hace la consulta con los datos que quiero que pasen al arduino, los guardo en variables y luego simplemente hace un echo uniendo todas las variables,
separndolas por comas para luego en el cdigo del Arduino poder guardarlas en variables diferentes (cosa que an est por hacer).
Ahora a ver si lo pongo todo junto en el mismo cdigo y empiezo a separar las variables.
Un saludo.
Navigation
[0] Message Index

28/08/2014 14:38

S-ar putea să vă placă și