Error sending arduino data to my local server

1

I have a problem to send my sensor data to a local server, I had already tested it with a single sensor and it worked for me, it was the lm35, now that it adds another sensor I can not send the data, in arduino it tells me that everything is correct here I leave the codes to help me find my error

[DATABASE]

CREATE TABLE 'variable' (
  'fecha' datetime NOT NULL,
  'valor' float NOT NULL,
  'rutax' float NOT NULL,
  'rutay' float NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

[PHP CODE]

<?php
$mysql_servidor = "localhost";
$mysql_base = "sensor";
$mysql_usuario = "root";
$mysql_clave = "";

$valor = htmlspecialchars($_GET["valor"],ENT_QUOTES);
$rutax  = htmlspecialchars($_GET["rutax"],ENT_QUOTES);
$rutay = htmlspecialchars($_GET["rutay"],ENT_QUOTES);

// Valida que esten presente todos los parametros
if (($valor!="") and ($rutax!="") and ($rutay!=""))

{
    mysql_connect($mysql_servidor,$mysql_usuario,$mysql_clave) or die("Imposible conectarse al servidor.");
    mysql_select_db($mysql_base) or die("Imposible abrir Base de datos");   
    $sql = "insert into variable (fecha, valor, rutax, rutay) values (NOW(),'$valor','$rutax','$rutay')";
    mysql_query($sql);

}
?>

[arduino code]

#include <SPI.h>
#include <Ethernet.h>
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"
MPU6050 sensor;

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
EthernetClient client;
char server[] = "192.168.1.100";
unsigned long ultimaConexion = 0;
// Estado de la ultima conexion
boolean ultimoEstado = false;
const unsigned long intervaloConexion = 10000;
float tempC; // Temperatura en celsius
float acelx;
float acely;
int MPU6050 = 0;
int LM35 = 0;

int ax, ay, az;



void setup() {
  Serial.begin(57600); 
  sensor.initialize(); 
  Serial.println("Sensor de temperatura LM35");
  // Espera 1 segundo para que se inicie la tarjeta Ethernet
  Serial.println("Sensor de Acelerometro ");  
  delay(1000);
  Ethernet.begin(mac);
  // Imprime la direccion IP de la tarjeta
  Serial.print("Direccion IP: ");
  Serial.println(Ethernet.localIP());
}
// Loop principal
void loop() {
  // Lee la temperatura desde el sensor
  tempC = analogRead(LM35);

  // Convierte el valor leido a temperatura
  tempC = (5.0 * tempC * 100.0) / 1024.0;
  acelx = analogRead(MPU6050);
 acelx=atan(ax/sqrt(pow(ay,2) + pow(az,2)))*(180.0/3.14);
 acely = analogRead(MPU6050);
 acely=atan(ay/sqrt(pow(ax,2) + pow(az,2)))*(180.0/3.14);

 sensor.getAcceleration(&ax, &ay, &az);


  // Si hay datos que llegan por la conexion los envia a la puerta serial
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }


  if (!client.connected() && ultimoEstado) {
    Serial.println();
    Serial.println("Desconectando...");
    client.stop();
  }

  if (!client.connected() && (millis() - ultimaConexion > intervaloConexion)) {
    httpRequest();
  }
  ultimoEstado = client.connected();
}
void httpRequest() {
  if (client.connect(server, 8080)) {
    // Envia el dato al puerto serial
    Serial.print("Sensor LM35: ");
    Serial.print(tempC);
    Serial.println(" grados Celsius");
  Serial.print("Sensor Acelerometro: ");

  Serial.print(acelx); 
   Serial.print("Inclinacion en X: ");
   Serial.println(acely);
  Serial.print("tInclinacion en Y:");

    // Envia el requerimiento al servidor via GET
    Serial.println("Iniciando conexion...");
    client.print("GET http://192.168.1.100:8080/ARDUINO/sensorarduino.php?valor=&rutax=&rutay=");
    client.print(tempC);
    client.print(acelx);
    client.print(acely);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println("User-Agent: Arduino-Ethernet");
    client.println("Connection: close");
    client.println();   
    ultimaConexion = millis();
  }
  else {

    Serial.println("Error al conectarse al servidor");
    Serial.println("Desconectando...");
    client.stop();
  }
}

    
asked by Daniel 09.08.2017 в 10:18
source

1 answer

0

Server side (PHP):

The code that you sample does not have control measures to execute the SQL queries and you do not show anything in case the parameters are incorrect, so if something goes wrong you do not know what happened.

Here is an example of how to do it correctly:

<?php
$mysql_servidor = "localhost";
$mysql_base = "sensor";
$mysql_usuario = "root";
$mysql_clave = "";

// Valida que estén presente todos los parámetros
if (
    !empty($_GET["valor"]) && !empty($_GET["rutax"]) && !empty($_GET["rutay"])
) {
    $valor = mysql_real_escape_string($_GET["valor"]);
    $rutax = mysql_real_escape_string($_GET["rutax"]);
    $rutay = mysql_real_escape_string($_GET["rutay"]);
    mysql_connect($mysql_servidor, $mysql_usuario, $mysql_clave)
        or die("Imposible conectarse al servidor.");
    mysql_select_db($mysql_base)
        or die("Imposible abrir Base de datos");   
    $sql = "
        INSER INTO variable (
            fecha,
            valor,
            rutax,
            rutay
        ) values (
            NOW(),
            '$valor',
            '$rutax',
            '$rutay'
        )
    ";
    /* Guardamos el resultado de la ejecución de la consulta */
    $resultado = mysql_query($sql);
    /* Si ha fallado (devuelve "false") informamos del error */
    if ($resultado === false) {
        die(mysql_error());
    }
    die("Registros insertados: ". mysql_affected_rows());
}
die("Parámetros incorrectos");
?>

In this way, not only will an informational message appear when the connection to the MySQL server or database selection fails, information of the inserted record will appear (if it could be inserted), if the parameters are not defined and any errors that are generated in the query (duplicated key, full disk, syntax error, etc.).

I strongly recommend migrating your code to PDO / MySQL or mysqli . The mysql_* functions are marked as obsolete in PHP 5.5 and permanently removed from PHP 7.

Client side (Arduino):

The HTTP request is mounted incorrectly (thanks @Xerif for the track). The modifications that I proposed to you in PHP would detect the problem with the message "Incorrect parameters" .

The first line of the HTTP request that you generate would be of the form:

GET http://192.168.1.100:8080/ARDUINO/sensorarduino.php?valor=&rutax=&rutay=<tempC><acelx><acely> HTTP/1.1

The valor and rutax fields are sent empty and the rutay field receives all the concatenated numbers. The objective would be to mount the petition like this:

GET http://192.168.1.100:8080/ARDUINO/sensorarduino.php?valor=<tempC>&rutax=<acelx>&rutay=<acely> HTTP/1.1

To mount the HTTP request correctly you can use the following code:

void httpRequest() {
  if (client.connect(server, 8080)) {
    // Envia el dato al puerto serial
    Serial.print("Sensor LM35: ");
    Serial.print(tempC);
    Serial.println(" grados Celsius");
    Serial.println("Sensor Acelerometro:"); 
    Serial.print("Inclinacion en X: ");
    Serial.println(acelx);
    Serial.print("Inclinacion en Y: ");
    Serial.println(acely);

    // Envia el requerimiento al servidor via GET
    Serial.println("Iniciando conexion...");
    client.print("GET http://192.168.1.100:8080/ARDUINO/sensorarduino.php?valor=");
    client.print(tempC);
    client.print("&rutax=");
    client.print(acelx);
    client.print("&rutay=");
    client.print(acely);
    client.println(" HTTP/1.1");
    client.println("Host: " + server);
    client.println("User-Agent: Arduino-Ethernet");
    client.println("Connection: close");
    client.println();
    ultimaConexion = millis();
  } else {
    Serial.println("Error al conectarse al servidor");
    Serial.println("Desconectando...");
    client.stop();
  }
}
    
answered by 09.08.2017 / 10:43
source