Enviar iar va valore loress d deesde PH PHP/My /MySQL a Ard Ardu uino ino a trav ravés d dee In Interne rnet (S (SO...
http://f ://fo orum rum.ardu rduino. ino.ccc/in /index.php?topic= ic=97264.0;wap2 wap2
Enviar valores desde PHP /MySQL a Arduino a través de Internet (SOLUCIONADO) (SOLUCIONADO) (1/1) Hallenbeck : Hola,
Llevo unos días liado con este problema, a ver si me podéis echar un mano. Para empezar tengo esta configuración: configuración: -Arduino Mega(1280). IDE 1.0 -Ethernet Shield Shield w5100. -Sensores de temperatura DS18B20 y un par de LDRs. -Servidor Apache funcionando correctamente con P HP y MySQL sobre Windows 7 x64. Tengo un código (la idea es hacer una aplicación domótica domótica a t ravés de Internet, con interfaz Web) funcionando que manda los valores de los sensores a través de un script php que a su vez se comunica con la base de datos, añadiendo correctamente los valores. Hasta ahí perfecto, luego los muestro muestro en una página web alojada en el mismo mismo servidor Apache y voy actualizando los valores mediante mediante otros scripts php que hacen consultas a la base de datos. Ahora necesito mandar de vuelta a l Arduino algunos algunos valores para, por e jemplo, jemplo, 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 similar,, pero por el puerto serie, conectando el Arduino al ordenador que tiene alojado el servidor Apache. La idea es hacerlo independiente de ordena dores. Aquí los códigos: Arduino: Code: #include #include #include #include #include //*****************************************SENSOR //*****************************************S ENSOR TEMPERATU TEMPERATURA RA DS18B20*********** DS18B20*****************************************// ******************************// #define ONE_WIRE_BUS 4 //the onewire bus is connected to pin 4 on arduino #define TEMPERATUR TEMPERATURE_PRECISION E_PRECISION 10 //resolution of the sensors is set to 10bit(somehow won´t work) OneWire oneWire(ONE_WIRE_BU oneWire(ONE_WIRE_BUS); S); // setup a oneWire instance to communicate communicate with any OneWire devices // (not just Maxim/Dallas Maxim/Dallas temperature ICs) DallasTemperature DallasTemperature sensors(&oneWire); sensors(&oneWire); // Pass our oneWire reference to Dallas Temperature
//*****************************************ETHERNET*****************************************// byte mac[] = { 0x00, 0x11, 0x22, 0x33, 0xFB, 0x11 }; // Mac del dispositivo dispositivo ethernet byte ip[] = { 192, 168, 1, 18 }; // ip del dispositivo dispositivo ethernet //byte miServidor[] = { 192, 168, 1, 15 }; byte miServidor[]= 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; luzEncendida=false;
void setup(){ Wire.begin(); Serial.begin(9600); pinMode(pinLDR,INPUT); sensors.begin(); sensors.begin(); // start up the library for the DS18B20 int numSensors numSensors = sensors.getDeviceCount(); sensors.getDeviceCount(); // store store the number of sensors to the variable numSensors, numSensors, float temparray[numSensors]; temparray[numSensors]; // array with "numSensors" "numSensors" storage places for the temperature of each sensor // "sensors.getDeviceCount" is a function function in the library library
1d 6
28/08/2014 14 38
Enviar valores desde PHP/MySQL a Arduino a través de Internet (SO...
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
//*****************************************FUNCION PARA CONEXION PHP Y MANDAR DATOS*****************************************// void senddata(int numSensors, float temparray[]) {
2d 6
28/08/2014 14 38
Enviar valores desde PHP/MySQL a Arduino a través de Internet (SO...
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
Código PHP: (por si se puede ada ptar para que se manden las variables al Arduino) Code:
3d 6
28/08/2014 14 38
Enviar valores desde PHP/MySQL a Arduino a través de Internet (SO...
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, E ncendido, luzExterna) VALUES ( NOW(), $t0 , $t1, $luzInterna, $Encendido,$luzExterna)"); mysql_close($opendb); } ?> 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 pa rametro, 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 mañana.
Gracias por la respuesta! Hallenbeck : He llegado a una solución 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 #include //////////////////////////////////////////////////////////////////////// //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 addre ss (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(pa geValue); //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 ");
4d 6
28/08/2014 14 38
Enviar valores desde PHP/MySQL a Arduino a través de Internet (SO...
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 código espera recibir una serie de datos encerrados por < y >. El código php es el siguiente: Code: ' ?>
5d 6
28/08/2014 14 38
Enviar valores desde PHP/MySQL a Arduino a través de Internet (SO...
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, separándolas por comas para luego en el código del Arduino poder guardarlas en variables diferentes (cosa que aún está por hacer). Ahora a ver si lo pongo todo junto en el mismo código y empiezo a separar las variables. Un saludo. Navigation [0] Message Index
6d 6
28/08/2014 14 38