Para expertos en peticiones GET via web service a mysql

Hola todos,

Este código cuenta agujeros de tarjetas perforadas con un sensor infrarrojo utilizando un Sensor IR-FC 51 y un Arduino UNO, el monitor serial recoje la suma de lo que cuenta y trabaja a la perfección.

El próximo desafío es enviar estos datos a un web service obviamente con una Ethernet Shield W5100 conectado a internet y sensor de temperatura DTH11. Pero los ejemplos que encuentro toman valores constantes y no variables; como el que copio mas abajo.

Ya cree una base de datos mysql desde xampp, y puedo enviar valores escribiendo en la url: http://arduinoapc.php?contar=5 lo que me indica que mi base de datos está bien, pues registra cualquier valor.

Si realizo pruebas con códigos como myip o google search, se conecta y baja los datos sin problema.

En resumen son dos problemas: 1) no conecta el arduino con el web service (recibe el error 402 o 400 error connected - o indica que no reconoce la petición-), 2) no conecta el arduino con mysql.

Pero tampoco se como integrar la lectura del sensor en alguno de estos códigos.

Espero darme a entender bien.

Agradezco sus observaciones.

Gracias.

const int  buttonPin = A2;    // el pin a donde está conectado el sensor
const int ledPin = 13;       // el pin a donde está conectado el LED

// Variables will change:

int Cantidad = 0;            // contador de agujeros
int buttonState = 0;         // estado actual del contador
int lastButtonState = 0;     // estado previo del contador

// Variable de tiempo.
unsigned long t=0;

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT_PULLUP);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(115200);
}


void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  if (buttonState != lastButtonState) {
 
    if (buttonState == LOW) {
      // Cada vez que pulses el botón guardas millis en t.
      t = millis();
      Cantidad++;
      }
      else {
    }
    delay(10);
  }
  lastButtonState = buttonState;
 
  // Si el temporizador es distinto 0, significa que has pulsado el botón.
  if ( t!=0 ) {
    // Restas el tiempo actual con el de t, si el tiempo transcurrido
    // es mayor del que tu fijes (aquí un diez mili segundos), muestras la cantidad
    // y reinicias el temporizador.
    if ( millis() - t > 100 ) {         
      // Debemos tratar la cantidad.
      if ( Cantidad%5==0 && cantidad!==0 ) {
        Serial.print("Has pasado una tarjeta válida de ");
        Serial.print(Cantidad);
        Serial.println(" ");
        digitalWrite(ledPin, HIGH);
      }
      else {
        Serial.print("Error en la tarjeta, hemos contado ");
        Serial.print(Cantidad);
        Serial.println(" ");
        digitalWrite(ledPin, LOW);
      }
      // Debemos iniciar la cantidad y el timer.
      Cantidad=0;
      t=0;
    }
  }
}

Por ejempo he utilizado este código para tratar de insertar valores directamente (sin interfaces) a mysql sin lograrlo.

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "192,168,0,11";    // server ip

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 13);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield 10 second to initialize:
  delay(10000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /lector/arduinoapc.php?cantidad=");
    client.println("Host: 192, 168, 0, 11");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

También he intentado con ejercicios via web service infructuosos, como el código que acompaño.

#include <SPI.h>
#include <Ethernet.h>
#include "DHT.h"
#define DHTPIN 9
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = {192, 168, 1, 13 }; //Enter the IP of ethernet shield
byte serv[] = {192, 168, 1, 11} ; //Enter the IPv4 address
EthernetClient cliente;

void setup() {
Serial.begin(9600); //setting the baud rate at 9600
Ethernet.begin(mac, ip);
dht.begin();
}

void loop() {
float hum = dht.readHumidity(); //Reading the humidity and storing in hum
float temp = dht.readTemperature(); //Reading the temperature as Celsius and storing in temp
float fah = dht.readTemperature(true); //reading the temperature in Fahrenheit
float heat_index = dht.computeHeatIndex(fah, hum); //Reading the heat index in Fahrenheit
float heat_indexC = dht.convertFtoC(heat_index); //Converting the heat index in Celsius

 if (cliente.connect(serv, 80)) { //Connecting at the IP address and port we saved before
Serial.println("connected");
cliente.print("GET /ethernet/data.php?"); //Connecting and Sending values to database
cliente.print("temperature=");
cliente.print(temp);
cliente.print("&humidity=");
cliente.print(hum);
cliente.print("&heat_index=");
cliente.println(heat_indexC);

//Printing the values on the serial monitor
Serial.print("Temperature= ");
Serial.println(temp);
Serial.print("Humidity= ");
Serial.println(hum);
Serial.print("Heat Index= ");
Serial.println(heat_indexC);
cliente.stop(); //Closing the connection
}
else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
delay(5000);
}

Para los que han logrado enviar datos a mysql sin interfaces este sería el código, sin embargo no logro conectar a la base de datos.

#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(192, 168, 0, 11); // IP of the MySQL *server* here
char user[] = "root";              // MySQL user login username
char password[] = "";        // MySQL user login password

// Sample query
char INSERT_SQL[] = "INSERT INTO lector.arduino (valor) VALUES (' ')";
char query(128);
char valor;

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    delay(5000);
  }
  else
    Serial.println("Connection failed.");
}


void loop() {
  delay(2000);

  Serial.println("Recording data.");

  // Initiate the query class instance
  MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
  // Execute the query
  cur_mem->execute(INSERT_SQL);
  // Note: since there are no results, we do not need to read any data
  // Deleting the cursor also frees up memory used
  delete cur_mem;
}

Sus sugerencias son bienvenidas.

Gracias

LUISRO847:
Este código cuenta agujeros de tarjetas perforadas con un sensor infrarrojo utilizando un Sensor IR-FC 51 y un Arduino UNO, el monitor serial recoje la suma de lo que cuenta y trabaja a la perfección.

Yo veo varios errores en dicho codigo...

LUISRO847:
Ya cree una base de datos mysql desde xampp, y puedo enviar valores escribiendo en la url: http://arduinoapc.php?contar=5 lo que me indica que mi base de datos está bien, pues registra cualquier valor.

Suponiendo que servidor y cliente están en la misma red, solo tienes que añadir esto:

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress serv(192,168,1,11);
EthernetClient cliente;

void envia() {
   if (cliente.connect(serv, 80)) {
      Serial.println("connectado");
      cliente.print("GET /arduinoapc.php?contar=");   //Cadena de envio de datos
      cliente.print(Cantidad);                                    //Dato
   }else {
      Serial.println("coneccion fallo");
   }
}

Para enviar al servidor solo pones envia(); en el momento que quieres enviar datos al servidor.