Membaca Sensor DHT11 dan Menulis ke Database

Halo!
Disini saya akan menuliskan pengalaman saya membaca sensor dari DHT11 menggunaan ESP32, dan menuliskan data yang dibaca sensor ke dalam database.

Sumbernya dari sini:
https://randomnerdtutorials.com/esp32-esp8266-mysql-database-php/

Dalam percobaan ini, diperlukan
1. post-esp-data.php
2. esp-data.php
3. File yang akan diupload ke ESP32

Nah, untuk percobaan ini sebenarnya juga perlu melakukan web hosting, dan mendapatkan domain name sendiri, tapi saya tidak membuat karena sudah ada yang dapat digunakan oleh teman-teman sekelas.

File .php di atas akan dimasukkan di web yang sudah dibuat, untuk mengatur tampilan HTML dan melakukan pengisian database.


Di database sekelas itu, data yang diambil data suhu dalam celcius, tekanan, dan kelembapan. Nah, saya menggunakan DHT11 yang hanya bisa mengukur suhu dan kelembapan, jadi terdapat beberapa bagian dari program yang diganti.

1. post-esp-data.php
<?php
$servername = "localhost";

// REPLACE with your Database name
$dbname = "...";
// REPLACE with Database user
$username = "...";
// REPLACE with Database user password
$password = "...";

// Keep this API Key value to be compatible with the ESP32 code provided in the project page. 
// If you change this value, the ESP32 sketch needs to match
$api_key_value = "tPmAT5Ab3j7F9";

$api_key= $sensor = $location = $value1 = $value2 = $value3 = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $api_key = test_input($_POST["api_key"]);
    if($api_key == $api_key_value) {
        $sensor = test_input($_POST["sensor"]);
        $location = test_input($_POST["location"]);
        $value1 = test_input($_POST["value1"]);
        $value3 = test_input($_POST["value3"]);
        
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        
        $sql = "INSERT INTO SensorData (sensor, location, value1, value3)
        VALUES ('" . $sensor . "', '" . $location . "', '" . $value1 . "', '" . $value3 . "')";
        
        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } 
        else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
    
        $conn->close();
    }
    else {
        echo "Wrong API Key provided.";
    }

}
else {
    echo "No data posted with HTTP POST.";
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
2. esp-data.php
<!DOCTYPE html>
<html><body>
<?php

$servername = "localhost";

// REPLACE with your Database name
$dbname = ...;
// REPLACE with Database user
$username = ...;
// REPLACE with Database user password
$password = ...;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, sensor, location, value1, value3, reading_time FROM SensorData ORDER BY id DESC";

echo '<table cellspacing="5" cellpadding="5">
      <tr> 
        <td>ID</td> 
        <td>Sensor</td> 
        <td>Location</td> 
        <td>Value 1</td> 
        <td>Value 3</td>
        <td>Timestamp</td> 
      </tr>';
 
if ($result = $conn->query($sql)) {
    while ($row = $result->fetch_assoc()) {
        $row_id = $row["id"];
        $row_sensor = $row["sensor"];
        $row_location = $row["location"];
        $row_value1 = $row["value1"];
        $row_value3 = $row["value3"]; 
        $row_reading_time = $row["reading_time"];
        // Uncomment to set timezone to - 1 hour (you can change 1 to any number)
        //$row_reading_time = date("Y-m-d H:i:s", strtotime("$row_reading_time - 1 hours"));
      
        // Uncomment to set timezone to + 4 hours (you can change 4 to any number)
        //$row_reading_time = date("Y-m-d H:i:s", strtotime("$row_reading_time + 4 hours"));
      
        echo '<tr> 
                <td>' . $row_id . '</td> 
                <td>' . $row_sensor . '</td> 
                <td>' . $row_location . '</td> 
                <td>' . $row_value1 . '</td> 
                <td>' . $row_value3 . '</td>
                <td>' . $row_reading_time . '</td> 
              </tr>';
    }
    $result->free();
}

$conn->close();
?> 
</table>
</body>
</html>
3. File yang akan diupload ke ESP32
#ifdef ESP32
  #include <WiFi.h>
  #include <HTTPClient.h>
#else
  #include <ESP8266WiFi.h>
  #include <ESP8266HTTPClient.h>
  #include <WiFiClient.h>
#endif

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include "DHT.h"

// Replace with your network credentials
const char* ssid     = "...";
const char* password = "...";

// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = ".../012-post-esp-data.php";

// Keep this API Key value to be compatible with the PHP code provided in the project page.
// If you change the apiKeyValue value, the PHP file /post-esp-data.php also needs to have the same key
String apiKeyValue = "tPmAT5Ab3j7F9";

String sensorName = "DHT11";
String sensorLocation = "012(Jakarta)";

#define DHTPIN 4
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);
 
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());

  dht.begin();

}

void loop() {
  //Check WiFi connection status
  if(WiFi.status()== WL_CONNECTED){
    HTTPClient http;
   
    // Your Domain name with URL path or IP address with path
    http.begin(serverName);
   
    // Specify content-type header
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
   
    // Prepare your HTTP POST request data
    String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName
                          + "&location=" + sensorLocation + "&value1=" + String(dht.readTemperature())
                          + "&value3=" + String(dht.readHumidity()) + "";
    Serial.print("httpRequestData: ");
    Serial.println(httpRequestData);

    // Send HTTP POST request
    int httpResponseCode = http.POST(httpRequestData);
   
    // If you need an HTTP request with a content type: text/plain
    //http.addHeader("Content-Type", "text/plain");
    //int httpResponseCode = http.POST("Hello, World!");
   
    // If you need an HTTP request with a content type: application/json, use the following:
    //http.addHeader("Content-Type", "application/json");
    //int httpResponseCode = http.POST("{\"value1\":\"19\",\"value2\":\"67\",\"value3\":\"78\"}");
       
    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    // Free resources
    http.end();
  }
  else {
    Serial.println("WiFi Disconnected");
  }
  //Send an HTTP POST request every 30 seconds
  delay(30000); 
}


Nah, sebenarnya sensornya sudah membaca setiap 30 detik, dan sudah muncul tulisan yang menandakan sensor berhasil membaca di serial monitor.

Namun, tampilannya tetap terlihat seperti ini:


Namun, saya belum menemukan letak kesalahannya di mana. Nanti akan saya update di blog ini jika saya menemukan penyebab kesalahannya. Terima kasih

Komentar

Postingan populer dari blog ini

DHT 11 dan Sensor LCD

Rumah Anti Maling dengan Sensor Ultrasonic dan ESP32

Bluetooth for ESP32