使用nodeMCU在mysql中无法写入dht11传感器

时间:2019-03-16 14:51:40

标签: php mysql arduino esp8266 nodemcu

我无法使用带有nodeMCU(ESP8266MCU)的PHP + MYSQL编写通过DHT11传感器收集的数据。

在串行监视器上说无法连接到服务器并且不执行get命令

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <SimpleDHT.h>

// WiFi - Coloque aqui suas configurações de WI-FI
const char ssid[] = "WIFI-D767480";
const char psw[] = "986557D124D480";

// Site remoto - Coloque aqui os dados do site que vai receber a requisição GET
const char http_site[] = "192.168.23.1";
const int http_port = 80;

// Variáveis globais
WiFiClient client;
IPAddress server(192,168,23,1); //Endereço IP do servidor - http_site
int pinDHT11 = D2;
SimpleDHT11 dht11;

void setup() {
  delay(30000); //Aguarda 30 segundos 
  Serial.begin(9600);
  Serial.println("NodeMCU - writing data in BD via GET");
  Serial.println("Waiting connection");

  // Tenta conexão com Wi-fi
  WiFi.begin(ssid, psw);
  while ( WiFi.status() != WL_CONNECTED ) {
    delay(100);
    Serial.print(".");
  }
  Serial.print("\nWI-FI sucefull connection: ");
  Serial.println(ssid);

}

void loop() {

  //Leitura do sensor DHT11
  delay(3000); //delay entre as leituras
  byte temp = 0;
  byte humid = 0;
  if (dht11.read(pinDHT11, &temp, &humid, NULL)) {
    Serial.print("Fail in sensor.");
    return;
  }

  Serial.println("writing data in BD: ");
  Serial.print((int)temp); Serial.print(" *C, "); 
  Serial.print((int)humid); Serial.println(" %");

  // Envio dos dados do sensor para o servidor via GET
  if ( !getPage((int)temp,(int)humid) ) {
    Serial.println("GET request failed");
  }
}

// Executa o HTTP GET request no site remoto
bool getPage(int temp, int humid) {
  if ( !client.connect(server, http_port) ) {
    Serial.println("Failed to connect to site ");
    return false;
  }
  String param = "?temp=" + String(temp) + "&humid=" + String(humid); //Parâmetros com as leituras
  Serial.println(param);
  client.println("GET /weather/insert_weather.php" + param + " HTTP/1.1");
  client.println("Host: ");
  client.println(http_site);
  client.println("Connection: close");
  client.println();
  client.println();

    // Informações de retorno do servidor para debug
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }
  return true;
}

我试图修改以下行,但没有成功:

client.println("GET /weather/insert_weather.php" + param + " HTTP/1.1");

用于:client.println(“ GET /weather/insert_weather.php” + param); 和:client.println(“ GET /weather/insert_weather.php?+param+\r\n”);

错误出现在附件图像中enter image description here 我也尝试了其他代码,但没有成功。

我的php代码是:

<?php
$temp = filter_input(INPUT_GET, 'temp', FILTER_SANITIZE_NUMBER_FLOAT);
$humid = filter_input(INPUT_GET, 'humid', FILTER_SANITIZE_NUMBER_FLOAT);
if (is_null($temp) || is_null($humid) ) {
  //Gravar log de erros
  die("Dados inválidos");
} 
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "maker";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
  //Gravar log de erros
  die("Não foi possível estabelecer conexão com o BD: " . $conn->connect_error);
} 
$sql = "INSERT INTO weather (wea_temp, wea_humid) VALUES ($temp,$humid)";

if (!$conn->query($sql)) {
  //Gravar log de erros
  die("Erro na gravação dos dados no BD");
}
$conn->close();
?>

我正在使用WAMP v.3.1.17 给你加油!

1 个答案:

答案 0 :(得分:0)

尝试使用POST请求而不是GET,并在您的PHP代码中使用$ _POST [myvariable]来获取HTTP请求主体的内容。此外,您可以获得用于ESP8266的HTTP library,具有用于发送HTTP请求的功能。这是我其中一个项目的摘要,其中我所做的几乎与您现在尝试做的完全一样

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status

  HTTPClient http;    //Declare object of class HTTPClient

  postData = "reading=" + readingData + "&data=" + ADCData; //create the string that 
  // will be sent in the POST request

  http.begin("http://192.168.0.179:80/phptesting.php");      //Specify request 
  destination
  //send it to a .php file which can extract data from POST requests.

  http.addHeader("Content-Type", "application/x-www-form-urlencoded");  //Specify 
  //  content-type header

  int httpCode = http.POST(postData);   //Send the request
  String payload = http.getString();                  //Get the response payload

  Serial.println(httpCode);   //Print HTTP return code
  Serial.println(payload);    //Print request response payload. If you get anything 
  besides '200' something is up.

  http.end();  //Close connection

尝试一下,如果它不起作用,请告诉我,我可以将这个项目的其余代码发送给您。