Project 9 : Database
Hallo kembali lagi di medium saya Pramaditya Fajri Migfar dari ITB dengan NIM 18221111. Hari ini saya kembali lagi untuk mengerjakan project embedded tentang database. Meskipun ini hanyalah project bonus, bukan wajib seperti project sebelumnya, tetap saja project kali ini tidak kalah menarik dari project-project sebelumnya. Langsung saja kita masuk ke alat dan bahan yang diperlukan untuk project kali ini.
Alat dan Bahan.
- ESP32
- Kabel Micro USB
- Laptop
- Breadboard
- BMP180
- Kabel Jumper
Proses.
Langkah pertama yang diperlukan untuk project ini adalah menentukan domain dan hosting server, setelah bertanya ke teman-teman saya ternyata banyak dari mereka menggunakan https://www.000webhost.com/ karena itu langsung saja kita buka website tersebut danmelakukan sign up dan memberi nama pada project website yang akan dibuat. Kemudian, buat database baru pada menu Create New Database. Lalu, isi nama, username database, dan password.
Kemudian, klik Manage -> PhpMyAdmin -> SQL setelah itu masukkan query berikut.
CREATE TABLE SensorData (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
sensor VARCHAR(30) NOT NULL,
location VARCHAR(30) NOT NULL,
value1 VARCHAR(10),
value2 VARCHAR(10),
value3 VARCHAR(10),
reading_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)Lalu, akan muncul tampilan tabel SensorData yang telah dibuat. Kemudian selanjutnya adalah menciptakan script PHP yang akan menerima permintaan dari ESP32 dan memasukkan data-data hasil pembacaan ke dalam MySQL Database. Script-nya adalah sebagai berikut.
<?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 = "localhost";
// REPLACE with your Database name
$dbname = "REPLACE_WITH_YOUR_DATABASE_NAME";
// REPLACE with Database user
$username = "REPLACE_WITH_YOUR_USERNAME";
// REPLACE with Database user password
$password = "REPLACE_WITH_YOUR_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"]);
$value2 = test_input($_POST["value2"]);
$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, value2, value3)
VALUES ('" . $sensor . "', '" . $location . "', '" . $value1 . "', '" . $value2 . "', '" . $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;
}Untuk script di atas, saya menyalin kode yang telah disediakan oleh randomnerdstutorial dan menyimpannya dengan format post-esp-data.php yang kemudian diupload pada folder public_html. Lalu, saya menciptakan script PHP untuk menampilkan semua konten yang ada di dalam database ke website dengan script sebagai berikut.
<!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 = "localhost";
// REPLACE with your Database name
$dbname = "REPLACE_WITH_YOUR_DATABASE_NAME";
// REPLACE with Database user
$username = "REPLACE_WITH_YOUR_USERNAME";
// REPLACE with Database user password
$password = "REPLACE_WITH_YOUR_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, 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 2</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_value2 = $row["value2"];
$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_value2 . '</td>
<td>' . $row_value3 . '</td>
<td>' . $row_reading_time . '</td>
</tr>';
}
$result->free();
}
$conn->close();
?>
</table>
</body>
</html>Sama seperti sebelumnya, saya menyalin kode yang telah disediakan oleh randomnerdstutorial dan menyimpannya dengan format esp_data.php yang kemudian diupload pada folder public_html. Sehingga akan terlihat sebagai berikut.
Kemudian, tampilan scriptpost-data.php dapat dicek dengan mengakses website yourdomain.000webhost.com/esp-data.php dan akan muncul tampilan sebagai berikut.
Nah, kita berhasil melakukan setup pada website. Berikutnya, langsung saja kita ambil ESP32 kita untuk melakukan pembacaan temperatur, ketinggian, dan tekanan yang akan ditampilkan pada website. Untuk rangkaiannya adalah sebagai berikut.
Berikutnya, kita bisa mulaimenyusun kode program pada Arduino IDE. Untuk kodenya, diambil dari kode pada project empat namun ditambah dengan modifikasi agar bisa mengunggah pembacaan data ke database yang telah kita buat.
/*
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_BMP085.h>
// Replace with your network credentials
const char* ssid = "REPLACE-WITH-YOUR-SSID";
const char* password = "REPLACE-WITH-YOUR-PASSWORD";
// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "http://chintyaw.000webhostapp.com/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 = "BMP180";
String sensorLocation = "Kos";
#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BMP085 bmp; // I2C
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)
bool status = bmp.begin(0x76);
if (!status) {
Serial.println("Could not find a valid BMP180 sensor, check wiring or change I2C address!");
while (1);
}
}
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(bmp.readTemperature())
+ "&value2=" + String(bmp.readAltitude()) + "&value3=" + String(bmp.readPressure()/100.0F) + "";
Serial.print("httpRequestData: ");
Serial.println(httpRequestData);
// You can comment the httpRequestData variable above
// then, use the httpRequestData variable below (for testing purposes without the BMP180 sensor)
//String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BMP180&location=Home&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(5000);
}Klik upload dan akan tampak tampilan sebagai berikut pada serial monitor.
Setelah berhasil upload kode diatas, akses kembali yourdomain.000webhost.com/esp-data.php dan akan muncul tampilan hasil pembacaan ESP32 pada website.
Nahhh keren bukan??? Jadi di project ini, kita telah berhasil membaca data kondisi sekitar dan ditampilkan pada website, tetapi perbedaan pada project sebelumnya adalah kita memanfaatkan PHP, yakni post-esp-data.php yang digunakan untuk mengecek data dari server dan kemudian akan disimpan dalam database SQL yang sudah dibuat sebelumnya dan berikutnya adalah esp-data.php yang membaca data yang sebelumnya telah disimpan dalam database dan menampilkannya dalam bentuk website.
Get Pramaditya Fajri Migfar’s stories in your inbox
Join Medium for free to get updates from this writer.
Oke mungkin sekian untuk project kali ini tentang database, semoga bermanfaat dan sampai jumpa di project-project berikutnya. Terima kasih!!







