Ethernet Shield + XAMPP + PHP + MYSQL


hola, vengo pedir ayuda aquí ya que tras varios días de agobio e intentar encontrar una solución, me es imposible continuar y necesito una solución ya.
quiero que mi arduino envie datos de los sensores la web y almacene los datos en una bbdd, y además en base la temperatura obtenida se accionen los relés. bien, tengo el mismo código que el gran proyecto que hizo @eljamz , solo que yo no uso su sensor de temperatura ds18b20, por lo que de su código quité la función que usa para obtener la temperatura, la función e los reles lo dejé igual. aquí os dejo el proyecto del que os hablo-> http://forum.arduino.cc/index.php?topic=138024.0
bien, yo uso xampp(integracion de apache php y msql, pues no consigo hacer que se conecte la web creada (en mi caso 127.0.0.1/arduino_sensor.php o localhost/arduino_sensor.php ) tengo una pregunta sobre el código que os dejo continuacion
en byte server tengo que poner mi direccion ip local no? o tengo que poner la del servidor..osea 127.0.0.1?
ando bastante perdido en este tema..porque no logra conectarse la web y tengo ya configurado correctamente xampp
el código php en mi caso debería ir guardado en la siguiente ruta: c:\xampp\htdocs no?
de todas maneras modificando lo poco que os dicho, pero por puerto serial me sale: connecting... conection failed
aquí os dejo el código arduino
code: [select]
#include <ethernet.h>
#include <spi.h>
#include <onewire.h>

//ethernet configuration
byte mac[] = {0xde, 0xad, 0xbe, 0xef, 0xff, 0xee}; // ethernet shield mac
byte ip[] = { 192,168,1,249 }; // ethernet shield ip
byte server[] = { 192,168,1,16 }; // server ip

ethernetclient client;


//settings relays
string location = "http://192.168.1.16/arduino_sensor.php http/1.0";
char instring[32]; // string incoming serial data
int stringpos = 0; // string index counter
boolean startread = false; // reading?

//declare relay pinouts
int rel1pin = 3;  // setup realy 1 pin
int rel2pin = 4; // setup realy 2 pin

//define read sensor


float luminosidad;
int sensorluminosidad=3;


//void setup
void setup(void) {
 serial.begin(9600);
 ethernet.begin(mac, ip); // init ethernet shield
 pinmode(rel1pin, output); // make relpin , output
 pinmode(rel2pin, output); // make relpin , output
 delay(5000); // wait 5 seconds init program
}


//void loop
void loop(void) {
luminosidad = analogread(sensorluminosidad);
 luminosidad= (luminosidad)/10;
 serial.print("la luminosidad actual es (0-100%) "); // nos escribe por el puerto serie la temperatura existente
 serial.println(luminosidad);
delay(500); //just here slow down output easier read
string pagevalue = connectandread(); //connect server , action follow!.
serial.println(pagevalue); //print out findings.
delay(500); //just here slow down output easier read
}


/*
function relays
*/
string connectandread(){
 //connect server

 serial.println("connecting...");

 //port 80 typical of www page
 if (client.connect(server, 80)) {
   serial.println("connected");
   client.print("get ");
   client.println(location);
   client.println();

   //connected - read page
   return readpage(); //go , read output

 }else{
   return "connection failed";
 }

}



string readpage(){
 //read page, , capture & return between '<' , '>'

 stringpos = 0;
 memset( &instring, 0, 32 ); //clear instring memory

 while(true){

   if (client.available()) {
     char c = client.read();

     if (c == '<' ) { //'<' our begining character
       startread = true; //ready start reading part
     }else if(startread){

       if(c != '>'){ //'>' our ending character
         instring[stringpos] = c;
         stringpos ++;
       }else{
         //got need here! can disconnect now
         startread = false;
         client.stop();
         client.flush();
         serial.println("disconnecting.");
         
         int inrel = atoi (instring);
         if (inrel == 1) {
           digitalwrite(rel1pin, high);
           digitalwrite(rel2pin, low);
         } else if (inrel == 2) {
           digitalwrite(rel1pin, low);
           digitalwrite(rel2pin, high);
         }
         return instring;

       }

     }
   }

 }

}





//save temperature mysql
 serial.println("connecting...");

 if (client.connect(server, 80)>0) {  // connect server
   client.print("get /arduino_sensor.php?type=celsius&value="); // send data get
   client.print(luminosidad);
   client.println(" http/1.0");
   client.println("user-agent: arduino 1.0");
   client.println();
   serial.println("connected");
 }
 else
 {
   serial.println("connection fail");
 }
 if (client.connected()) {}
 else {
   serial.println("disconnected!");
 }
 client.stop();
 client.flush();
}

aquí el .php y mysql (iguales que los de @eljamz
code: [select]
<?php
include('db.php');
//get parameter sended by arduino.
$type $_get["type"];
$value $_get["value"];


// validate parameters if any and insert.
if (($type != "") && ($value != "")) {
mysql_query("insert into sensor (date, type, value) values (now(),'$type','$value')");
} else {

//if no parameters run script for relays.
$result mysql_query("select value from sensor order by date desc limit 1");
while(
$row mysql_fetch_array($result))
  {
$value $row['value'];
$value = (int)$value;
  }
}

if (
$value >= 28) { //this could be changed to anything, if you return <1> start relay 1 in pin3 and <2> start your second relay in pin 4.
echo "<1>";
} else {
echo "<2>";
}


mysql_close($con);
?>

code: [select]
create table `sensor` (
`id` int(10) not null auto_increment,
`date` datetime not null,
`type` varchar(100) not null collate 'latin1_spanish_ci',
`value` float not null,
primary key (`id`),
unique index `id` (`id`)
)
collate='latin1_spanish_ci'
engine=innodb
auto_increment=0;

por favor es importante y necesito presentarlo cuanto antes..gracias!

hola que tal

mac como ya lo tienes la mac address del ethernet shield
ip la direccion ip que se le va dar al ethernet shield
server la direccion la cual se va conectar el ethernet shield ya sea para leer o enviar informacion
correccion 127.0.0.1 es la direccion local de cada equipo o mejor conocido como localhost entonces no debes de poner ese ip

asi es como yo manejo las variables
code: [select]
ethernetclient cliente;

byte mac[] = {0x90, 0xa2, 0xda, 0x0d, 0x12, 0x73 };   // direccion mac del ethernet shield
ipaddress ip(192, 168, 1, 249);                       // direccion ip del ethernet shield
ipaddress mydns(192, 168, 1, 1);                      // direccion dns
ipaddress gate(192, 168, 1, 1);                       // direccion gateway
ipaddress mask(255, 255, 255, 0);                     // direccion subred
ipaddress servidor(192, 168, 1, 10);                  // direccion del servidor


y con esta funcion es donde hago la conexion al equipo
code: [select]
void httprequest(string param1)
{
  if(cliente.connect(servidor, 80))
  {
    cliente.print("get /campo/checador/che100.php?clave=");
    cliente.print(param1);
    cliente.println(" http/1.0");
    cliente.println("host: servidor-xp");
    cliente.println("user-agent: arduino-ethernet");
    cliente.println("connection: close");
    cliente.println("content-type: text/html");
    cliente.println();

    lastconnectiontime = millis();
  }
  else
  {
    cliente.stop();
  }
}


en tu caso solo es cuestion de cambiar la ruta /campo/checador/che100.php........

y una vez que el shield te cargue la pagina solo es cuestion de leer todo el contenido de la pagina

code: [select]
void leercadena(string param1)
{
  _cadena = "";
  while(cliente.available())
  {
    char c = cliente.read();
    _cadena += c;
  }
  if (!cliente.connected() && lastconnected)
  {
    cliente.stop();
  }

  if(!cliente.connected() && (millis() - lastconnectiontime > postinginterval))
  {
    httprequest(param1);
  }
  lastconnected = cliente.connected();
}


bueno mi script lo hice para consulta para verificar via rfid la entrada de trabajadores la empresa entonces lo que hago mando el numero de serie del tag una consulta en php la cual me verifica si el numero de serie esta asociado un numero de trabajador e identifica si ya entro o todavia no

saludos


Arduino Forum > International > Español > Proyectos (Moderators: surbyte, Hector_A) > Ethernet Shield + XAMPP + PHP + MYSQL


arduino

Comments

Popular posts from this blog

opencv3, tbb and rasp pi 2 - Raspberry Pi Forums

small ethernet problem - Raspberry Pi Forums

Multithumb configuration params not working? - Joomla! Forum - community, help and support