ESP32 Challenge #10: Sensor BMP280 X MySQL Database
Halo semuanya! Saatnya kita bermain dengan database nih. Penasaran, kan gimana caranya? Ikutin terus, yaa!
Sebelumnya, kita telah menampilkan hasil pembacaan sensor BMP280 ke sebuah web server. Nah, di challenge kali ini, kita akan menampilkan hasil pembacaan sensor BMP280 ke dalam database MySQL. Selamat mencoba!
—
DAFTAR KOMPONEN DAN PERANGKAT
Silahkan kalian siapkan komponen dan perangkat berikut:
- ESP32 Development Board (disini aku menggunakan ESP32 DOIT DEVKIT V1)
- Breadboard
- Sensor BMP280
- Kabel male to male (bisa disesuaikan)
- Micro USB Cable
- Laptop/komputer yang terdapat aplikasi Arduino IDE (sudah terinstall package board ESP32)
- Wi-Fi
- Hosting server and domain name
- PHP Application
- MySQL Database
—
DIAGRAM SKEMA
Untuk skemanya sendiri juga masih sama seperti pada challenge sebelumnya!
GPIO 22 (D22) terhubung dengan SCL sensor BMP 280, GPIO 21 (D21) terhubung dengan SDA sensor BMP 280, 3V3 terhubung dengan VCC sensor BMP 280, dan GND ESP32 terhubung dengan GND sensor BMP 280, serta Micro USB Cable digunakan untuk menghubungkan ESP32 Development Board dengan komputer/laptop kalian!
—
EKSPERIMEN DAN DEMO
FYI, aku menggunakan 000webhost.com sebagai hosting server. Pada platform ini kita bisa hosting tanpa dipungut biaya apapun, tetapi tentunya ada batasnya juga, ya, namanya juga gratis!:p
Nah, langkah-langkahnya gimana, nih?
- Buat account pada 000webhost.com
- Pilih upload your site dan kalian bisa berikan nama project kalian.
- Kemudian menuju ke halaman utama project seperti pada gambar di bawah ini.
4. Pilih Tool > Database Manager.
5. Kemudian kita buat database dengan nama database, username dan password bisa disesuaikan sesuai keinginan kalian yaa!
Jangan lupa mencatat nama DB, user DB, dan password DB-nya karena akan digunakan pada langkah2 selanjutnya!
6. Kemudian, klik bagian Manage > phpMyAdmin.
7. Setelah itu, kalian akan diminta log in phpMyAdmin, silahkan isikan user DB dan password yang telah kalian catat sebelumnya. Kemudian, kita akan membuat tabel dengan nama SensorData. Atribut-atribut tabel tersebut adalah id, sensor, location, value1, value2, value3, dan reading_time. Berikut adalah syntax yang digunakan.
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
)
8. Setelah itu klik “Go” dan tabel baru akan berhasil dibuat dengan atribut sesuai pada langkah 7. Tentu saja tabelnya masih kosong karena kita belum mengisinya dengan suatu nilai.
9. Setelah itu, kembali ke menu utama project lalu pilih File Manager.
10. Akan terdapat 2 folder, yaitu public_html dan tmp.
11. Nah, silahkan buka folder public_html. Kemudian, tombol new file pada bagian kanan atas.
12. Kita akan membuat file index.php dengan kode program dibawah.
<?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;
}
Nah, jangan lupa kalian ganti bagian ini dengan nama DB, user DB, dan password yang telah kalian catat sebelumnya.
// 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";
Jika sudah, klik tombol save & close.
13. Kemudian, kita buat file esp-data.php dengan kode program di bawah ini.
<!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>
Seperti sebelumnya, jangan lupa mengganti dbname, username, dan passwordnya sesuai dengan yang kalian catat yaa! Kemudian, klik save & close.
14. Kemudian, pada menu utama project, pilih Website Settings> General.
Akan terdapat nama website kalian.
15. Jika https://projectseitb.000webhostapp.com/esp-data.php dibuka, maka akan muncul seperti gambar berikut.
16. Jika https://projectseitb.000webhostapp.com/esp-data.php dibuka, maka akan muncul tabel SensorData.
Nah, setelah hosting server dan database sudah siap, langsung aja kita buka aplikasi Arduino IDE kita.
17. Silahkan copy paste link berikut pada aplikasi Arduino IDE.
/*
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 <Adafruit_BME280.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://example.com/index.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 = "BME280";
String sensorLocation = "Office";
/*#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_BMP280 bmp; // I2Cvoid 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 BMP280 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(SEALEVELPRESSURE_HPA)) + "&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 BMP280 sensor)
//String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BMP280&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);
}
Keterangan program:
#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 <Adafruit_BME280.h>
Seperti biasa pada awal program kita harus mengimpor semua library yang ingin kita gunakan.
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
Jangan lupa mengganti SSID dengan nama WiFi dan password dengan password WiFi kalian yaa.
const char* serverName = "http://example.com/index.php";
serverName diisi dengan nama website yang telah kalian buat sebelumnya.
String apiKeyValue = "tPmAT5Ab3j7F9";
String sensorName = "BME280";
String sensorLocation = "Office";
Kemudian set variabel yang mungkin ingin kalian ubah, yaitu apiKeyValue, sensorName, atau sensorLocation. ApiKeyValue adalah sebuah String random yang bisa dimodifikasi, berfungsi untuk alasan keamanan. Jika memiliki API Key maka dapat mempublikasikan data ke database kalian.
Serial.begin(115200);
Pada bagian setup, inisialisasi komunikasi serial dengan kecepatan 115200 baud.
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());
Kemudian, akan dicek apakah WiFi sudah connect, jika sudah, akan ditampilkan IP Address.
bool status = bmp.begin(0x76);
if (!status) {
Serial.println("Could not find a valid BMP280 sensor, check wiring or change I2C address!");
while (1);
}
Selain itu, dilakukan inisialisasi bmp dan kemudian dicek apakah sensor dapat terbaca, jika tidak maka akan menampilkan error message.
Kemudian, pada bagian loop, akan dicek WiFi connection status, jika sudah terhubung maka hasil pembacaan temperatur, ketinggian dan tekanan akan dikirimkan setiap 30 detik.
18. Lalu, klik verify dan compile. Buka Tools > Serial Monitor. Kemudian muncul HTTP Response Code: 200 (OK).
19. Kemudian, silahkan buka https://projectseitb.000webhostapp.com/esp-data.php dan kalian bisa melihat hasil pembacaan sensor BMP280.
Kalian juga bisa mengecek hasil pembacaan pada tabel SensorData melalui phpMyAdmin.
—
HASIL EKSPERIMEN DAN ANALISIS
Eksperimen kali ini cukup menantang tetapi sangat seru! Pada eksperimen kali ini, aku belajar banyak hal baru dan cukup lama menyediakan waktu untuk mengotak-atik.
Masalah pertama yang aku hadapi adalah karena aku menggunakan hosting server yang berbeda dengan referensi yang aku gunakan, yaitu https://randomnerdtutorials.com/esp32-esp8266-mysql-database-php/, aku harus menyesuaikan dengan hosting server tersebut, sehingga perlu mengganti nama post-esp-data.php menjadi index.php. Karena ketika aku menggunakan post-esp-data.php, saat aku membuka websitenya, muncul pesan seperti gambar berikut.
Masalah kedua yang aku alami adalah server MySQL Database sering kali tidak berjalan dengan baik, sehingga sangat sulit untuk melalukan login pada phyMyAdmin, aku juga tidak tahu pasti kenapa hal tersebut terjadi, karena username dan password yang aku berikan sudah benar, dugaanku mungkin karena banyak yang sedang mengakses sehingga servernya mengalami down. Namun, aku lupa untuk me-screenshot bukti error-nya. Tetapi, setelah aku menunggu beberapa saat dan mencoba login kembali, aku dapat mengakses databasenya dan sudah terdapat data hasil pembacaan sensor pada tabel SensorData.
Itu dia challenge ke-10. Gimana sudah cukup menantang, bukan? Sampai jumpa di challenge berikutnya!