【问题标题】:Fail writing dht11 sensor in mysql with nodeMCU使用nodeMCU在mysql中写入dht11传感器失败
【发布时间】:2019-03-16 14:51:39
【问题描述】:

我在使用 PHP + MYSQL 和 nodeMCU (ESP8266MCU) 写入通过 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");

for: 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 坦克你!

【问题讨论】:

  • 警告:您对SQL Injections 持开放态度,应该真正使用参数化的prepared statements,而不是手动构建查询。它们由PDOMySQLi 提供。永远不要相信任何类型的输入,尤其是来自客户端的输入。即使您的查询仅由受信任的用户执行,you are still in risk of corrupting your data
  • 我使用了虚构的地址,但感谢您的警告

标签: php mysql arduino esp8266 nodemcu


【解决方案1】:

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

 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

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

【讨论】:

  • 你能把这个项目的完整代码发给我吗?我这个问题很久了,没有找到解决办法=(你能把PHP代码也发给我吗??我也将不胜感激
  • 这里是我的项目的链接。这几乎完全符合您现在正在尝试做的事情。如果您需要更多帮助,请告诉我github.com/Skytrobb/Changing-HTML-Elements-With-Arduino?files=1
猜你喜欢
  • 2017-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多