ESP32 Journey — ESP32 Sensor Reading Database

Muhamad Ihza
ESP32 Journey
Published in
6 min readApr 26, 2020

Haloo guyss, jadii kali ini gue bakal cerita tentang pengalaman bikin database buat pembacaan sensor di ESP32. Nah, tapi sebelum itu ada sedikit kabar buruk tentang journey kali ini. Ya, bisa dibilang mungkin ini edisi terakhir dari ESP32 Journey, ya sekaligus mengakhiri rangkaian perjalanan dalam mengoprek ESP32 ini di mata kuliah Embedded System. Tapii kalian gaperlu sedih, karena semoga aja gue bisa nerusin perjalanan mengoprek di Medium ini dengan bidang lainnya, jadi kita akan coba explore hal lain diluar ESP32. Tapi doain dulu yak semoga gue mau dan mampu, hehehe.

Oke jadi pada kali ini saya dan Garin Ichsan akan mencoba membuat database untuk pembacaan sensor DHT11 pada ESP32. Ini cukup mirip dengan Journey Data Logging, tapi kali ini kita akan memasukannya ke database yang kita buat, dan dengan ini berarti kita bisa melakukan improvement.

Okey, seperti biasa komponen yang kita butuhin yaitu:
-ESP32 development board
-DHT22 or DHT11 Temperature and Humidity Sensor
-Resistor 10k ohm
-Breadboard
-Kabel jumper

Dan untuk skematiknya kaya gini nih.

source: randomnerdtutorials.com

Okey, langkah selanjutnya yakni kita akan melakukan konfigurasi terhadap database yang bakal kita bangun. Untuk kali ini, gue dan Garin bakal pake hosting punya temen kelas dan nyimpen data hasil pembacaan sensor dari anak” kelas. Niatnya sih kita pengen bikin weather station dari berbagai daerah di Indonesia yang berasal dari anak-anak STI 2018, keren banget kan.

Pada percobaan kali ini kita bakal gunain MySQL database untuk nyimpen datanya. Tahapan pertama yang harus dilakuin yaitu bikin tabel, nah pada kali ini database kelas kita ini di tabelnya terdapat ID, Jenis Sensor, Lokasi, Temperature, Pressure, dan Humidity. Oiya, kita kan pakenya DHT11 nih, jadi ya kita gaperlu ngisi field Pressure karena ya DHT11 ini ga sabi nih buat ngedetect gituan.

Langkah selanjutanya kita bikin 2 file PHP. Yang satu buat nerima data untuk database di Internet, dan yang satu lagi buat divisualisasikan di internet browser. Yaudahlah tanpa basa basi ini dia kode program PHP buat nerima data. Kalian cocokin sesuai kebutuhan aja yak.

<?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;
}

Kalo yang di bawah ini buat visualisasi di web browser.

<!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>

Okey, kita berhasil melakukan konfigurasi untuk pembangunan database, selanjutnya kita upload kode program pembacaan sensor DHT11 ke ESP32. Nih kode programnya saya kasih lagi, gratis.

#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>

#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT11 or DHT22
DHT dht(DHTPIN, DHTTYPE);

// Replace with your SSID and Password
const char* ssid = ...;
const char* password = ...;

// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = ".../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 = "Garin(Karanganyar)";

void setup() {
Serial.begin(115200);
delay(2000);// initialize DHT Sensor
dht.begin();

// Connect to WiFi
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("\nWiFi Connected");
Serial.println("IP Address: ");

// Local IP Address
Serial.println(WiFi.localIP());

}

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 (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 ... milisecond
delay(1 * 60 * 1000);
}

Selesai deh, tinggal upload dan taraa data akan disimpan ke dalam database. Nih buktinya nih.

Oiya, kalian bisa cek hasilnya disini nih: http://hardyvalen.my.id/18218050/18218050-esp-data.php

Yahh, dengan ini berakhir sudah rangkaian cerita kita di ESP32 Journey, senang dan sedih rasanya. Senang karena tugasnya selesai, tapi sedih karena gaada tuntutan buat ngoprek ESP32 lagi. Tapi sebisa mungkin deh aku mau explore hal lain lagi dan semoga bisa bagiin cerita lagi ke kalian. Jangan lupa untuk Stay Safe dan #DiRumahAja.

SEE YOU!

--

--

Muhamad Ihza
ESP32 Journey

Information and System Technology ITB student, have an enthusiast in technology.