Wheater Station — Database

Ichsan Sholeh
ESP32 DEVKIT — AR Tech
8 min readApr 24, 2020

24 April 2020.

Halo! Selamat datang kembali di tulisan gua kali ini. Tulisan ini akan berisikan project terakhir yang gue kerjakan pada semester ini untuk mata kuliah ‘Sistem Embedded’. Huhu gak kerasa 1 semester udah gue jalanin dengan menuliskan blog yang (semoga) bermanfaat kayak gini secara rutin :).

Tapi tenang aja, walaupun mungkin ini jadi project terakhir gue untuk mata kuliah ‘Sistem Embedded’ ini, tapi gak akan menutup kemungkinan kalo gue akan melanjutkan menulis hal-hal yang berbau mikrokontroller kayak gini lagi huehue. Doain aja semoga kedepannya ada waktu dan niatnya ya hehehe.

Sama seperti di tulisan sebelumnya juga, project ini gue kerjain bersama kelompok gue via google meet.

Dan sama seperti tulisan gue yang sebelumnya juga, karena langkah-langkah untuk mengerjakan project kali ini cukup sulit menurut gue, dan gue takut salah dalam menyampaikan tutorialnya, maka pada tulisan ini gue gak akan nulisin tutorialnya secara jelas, namun lebih ke garis besar dan experience yang gue dapatkan ketika ngerjain project ini. Tapi tenang aja. Kalo kalian emang mau ngerjain project ini dan mau liat tutorialnya, kalian bisa baca di “ESP32/ESP8266 Insert Data into MySQL Database using PHP and Arduino IDE”. Oke sekarang kita langsung aja deh huehue.

Overview

Gambar dibawah merupakan gambaran besar yang akan kita lakukan pada project kali ini.

Source: https://randomnerdtutorials.com/esp32-esp8266-mysql-database-php/

Tujuan dari project kali ini adalah kita akan menggunakan domain server dan akun hosting kita sendiri untuk menyimpan hasil pembacaan dari sensor yang dilakukan oleh ESP32. Nantinya, kita juga dapat melihat hasil pembacaan tersebut dari manapun dengan mengakses domain server tersebut.

Alat dan Bahan

Nah sebelum ngerjain project gue kali ini, berikut adalah alat-alat yang akan gue gunakan:
1. Laptop
2. ESP32
3. DHT11/22
4. Arduino IDE
5. Kabel jumper
6. Kabel micro USB
7. Breadboard
Berikut penampakannya:

Alat dan Bahan

Skema Rangkaian

Sama sseperti project sebelumnya, pada project ini, skema rangkaian yang gue gunakan mirip seperti skema rangkaian pada project gue yang bisa dilihat di “Web Server Arising”. Berikut adalah skemanya:

Sumber: https://randomnerdtutorials.com/esp32-dht11-dht22-temperature-humidity-web-server-arduino-ide/#more-39319

Dokumentasi:

Kode Program

Pada projcet ini, kurang lebih langkah-langkah yang gue lakukan sama dengan langkah-langkah yang ada pada tulisan di “ESP32/ESP8266 Insert Data into MySQL Database using PHP and Arduino IDE”, termasuk dengan kode programnya. Hanya saja, karena ini project terakhir dan memerlukan biaya untuk menggunakan hosting, maka pada project kali ini, kelas gue menggunakan sebuah domain dan akun hosting secara komunal. Asik gak tuh. Nah, berhubung domain, akun hosting dan skema kasar dari relasi basis data yang akan digunakan ini udah dibuat sama temen gue yang bernama Hardy, oleh karena itu gue cukup menambahkan program untuk menerima hasil bacaan dari sensor ESP32 gue ini, ke domain yang udah ada.

Alhasil, gue cuma perlu menambahkan 3 potongan kode untuk project ini. Potongan kode yang pertama adalah program php yang akan digunakan untuk menampilkan data pada basis data. Berikut potongan kodenya:

<!DOCTYPE html>
<html><body>
<?php
/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
$servername = "********";// 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, value2, 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>Temperature</td>
<td>Humidity</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_value2 = $row["value2"];
$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_value2 . '</td>
<td>' . $row_reading_time . '</td>
</tr>';
}
$result->free();
}
$conn->close();
?>
</table>
</body>
</html>

Lalu, terdapat potongan kode kedua yang berguna untuk mengirimkan hasil data bacaan tersebut pada basis data. Berikut potongan kodenya:

<?php
// Ichsan Sholeh Abdurrahim - 18218026
/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
$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 = "******";
$api_key= $sensor = $location = $value1 = $value2 = "";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"]);
$value2 = test_input($_POST["value2"]);

// 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, value2)
VALUES ('" . $sensor . "', '" . $location . "', '" . $value1 . "', '" . $value2 . "')";

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

Lalu, potongan kode yang terakhir adalah yang akan digunakan pada sketch yang akan diupload ke ESP32. Berikut potongan kodenya:

/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/#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>
#include <Adafruit_BME280.h>
#define DHTPIN 32 // Digital pin connected to the DHT sensor#define DHTTYPE DHT11 // DHT 11DHT dht(DHTPIN, DHTTYPE);// Replace with your network credentials
const char* ssid = "Gedung_B1";
const char* password = "Putra123";
// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "https://hardyvalen.my.id/18218026/post-esp-026-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 = "Ichsan(Bandung)";
/*#include <SPI.h>
#define BME_SCK 18
#define BME_MISO 19
#define BME_MOSI 23
#define BME_CS 5*/
#define SEALEVELPRESSURE_HPA (1013.25)Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
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());
// (you can also pass in a Wire library object like &Wire2)
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())
+ "&value2=" + String(dht.readHumidity()) + "";
Serial.print("httpRequestData: ");
Serial.println(httpRequestData);

// You can comment the httpRequestData variable above
// then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)
//String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";
// 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);
}

Testing

Setelah mengatur skema dan kode yang akan digunakan telah siap, maka selanjutnya kita dapat mencoba menjalankan program tersebut dengan menguploadnya ke ESP32. Selanjutnya jika berhasil, maka pada serial monitor akan ditampilkan pesan sebagai berikut:

Lalu berikut adalah tampilan apabila akan mengakses file yang berisikan program untuk mengirimkan data hasil sensor ESP32:

Dan apabila kita membuka file yang dapat memvisualisasikan data yang sudah disimpan, maka tampilannya akan sebagai berikut:

Voila! selesai deh untuk project kali ini. Pada saat mengerjakan project ini gue mungkin sempet mengalalami kesulitan ketika membaca instruksi di tutorial yang linknya udah gue taro diatas tadi. Karena mungkin ini emang pertama kalinya gue ngurusin hal-hal yang berkaitan dengan hosting dan domain ini. Tapi, beruntungnya karena gue ada teman untuk dijadiin tempat gue bertanya soal project ini yaitu Hardy, jadi gue alhamdulillah tetap berhasil deh ngerjain project ini huehue. Oiya, berikut adalah dokumentasi dari tampilan relasi dan organisasi file pada domain:

Berikut juga adalah dokumetasi pada saat pengerjaan project ini bersama dengan kelompok gue via google meet:

Yaaa, jadi mungkin sampai sini dulu tulisan gue di project terkhir ini, semoga usaha gue selama ini bisa bermanfaat untuk kalian serta untuk gue juga. Doain ya semoga indeks akhir gue ini bisa A HEHEHEHEHE.

Sekali lagi,

Semoga bisa bermanfaat, semoga kita semua sehat selalu,

Enjoy!

--

--

Ichsan Sholeh
ESP32 DEVKIT — AR Tech

Information System and Technology Student at Bandung Institute of Technology