Muy buenas a todos. Necesitaría ayuda con unos comandos para php y mysql.
Tengo este código que funciona muy bonito, en un wemos mini d1.
Lo que hace en resumidas cuentas es esperar a que se active un interruptor y enviar un dato, por php a una base de datos mysql.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
//-------------------VARIABLES GLOBALES--------------------------
bool countingTime = false; //to know if the variable has not changed below the threshold
bool gotTrigger = false; // thing was activated, waiting for button release
uint32_t startBeing1orMore; //to save the milliseconds when the variable started to be 1 or more
int botonmotor = 0; //motor accionado
int datos = 0;
int contconexion = 0;
const char *ssid = "dedede";
const char *password = "xxxxxxx";
unsigned long previousMillis = 0;
char host[48];
String strhost = "192.168.137.1";
String strurl = "/tutorial/enviardatos.php";
String chipid = "";
//-------Función para Enviar Datos a la Base de Datos SQL--------
String enviardatos(String datos) {
String linea = "error";
WiFiClient client;
strhost.toCharArray(host, 49);
if (!client.connect(host, 80)) {
Serial.println("Fallo de conexion");
return linea;
}
client.print(String("POST ") + strurl + " HTTP/1.1" + "\r\n" +
"Host: " + strhost + "\r\n" +
"Accept: */*" + "*\r\n" +
"Content-Length: " + datos.length() + "\r\n" +
"Content-Type: application/x-www-form-urlencoded" + "\r\n" +
"\r\n" + datos);
delay(10);
Serial.print("Enviando datos a SQL...");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 10) {
Serial.println("Cliente fuera de tiempo!");
client.stop();
return linea;
}
}
// Lee todas las lineas que recibe del servidro y las imprime por la terminal serial
while(client.available()){
linea = client.readStringUntil('\r');
}
Serial.println(linea);
return linea;
}
//-------------------------------------------------------------------------
void setup() {
// Inicia Serial
Serial.begin(115200);
Serial.println("");
Serial.print("chipId: ");
chipid = String(ESP.getChipId());
Serial.println(chipid);
// Connect WiFi
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.hostname("Name");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Print the IP address
Serial.print("IP address: ");
Serial.print(WiFi.localIP());
pinMode(5, INPUT); //boton
pinMode(4, OUTPUT); //relay
delay(200);
}
//--------------------------LOOP--------------------------------
void loop() {
delay(50);
botonmotor = digitalRead(5);
if (botonmotor==LOW) {
if (!countingTime) {
startBeing1orMore = millis();
countingTime = true;
}
} else {
countingTime = false;
if (gotTrigger) // check for release after activation
{ gotTrigger = false;
datos = ((millis() - startBeing1orMore)/1000); //send to database
Serial.println(datos);
enviardatos("chipid=" + chipid + "&temperatura=" + datos);
digitalWrite(4,LOW); //apaga motor
delay(50);
}
}
if (countingTime && !gotTrigger && millis() - startBeing1orMore > 1500) {
digitalWrite(4, HIGH); //enciende motor
gotTrigger = true;
delay(50);
}
}
Este es el php.
<?php
$conexion = mysql_connect("localhost", "root", "root");
mysql_select_db("tutorial", $conexion);
mysql_query("SET NAMES 'utf8'");
$chipid = $_POST ['chipid'];
$temperatura = $_POST ['temperatura'];
mysql_query("INSERT INTO `tutorial`.`tabla` (`id`, `chipId`, `fecha`, `temperatura`, `DATE`, `TIME` ) VALUES (NULL, '$chipid', CURRENT_TIMESTAMP, '$temperatura', CURRENT_DATE(), CURRENT_TIME());");
mysql_close();
echo "Datos ingresados correctamente.";
?>
Eso funciona todo ok. Peeero ahora me gustaría agregarle un botón al wemos para que cuando sea presionado se elimine la última entrada de mysql. Este código lo tengo, es este:
delete from tabla
order by id desc limit 1
Peeeeeeero, no sé si debería crear una nueva función enviardatos(), llamarla enviardatos2() en wemos. Y por otro lado, no sé como se define esto en el archivo de php.
Este es el problema de andar copiando y pegando pedazos de código (resulta que no entiendo todo mi código obviamente.......), y ese tipo de cosas por ahora no las sé crear, a lo sumo hacer pequeñas modificaciones.
Un saludo a todos y gracias!