Ep 10 : ESP32 Database with MySQL and PHP

MySQL Database stores ESP32 with BME280 data

Bonaventura Bagas Sukarno
9 min readApr 12, 2021

Setelah melakukan eksperimen Weather Station ESP32 di blog sebelumnya, pada project kali ini akan dibangun MySQL database untuk menyimpan nilai pembacaan dari sensor BME280 dari sistem embedded ESP32.

Detail dari project ini yaitu dibuat web page sederhana untuk menampilkan pembacaan nilai sensor, timestamp, dan informasi dari database. Sistem ESP32 dengan sensor BME280 mengirimkan data ke MySQL database dengan command HTTP POST pada PHP script. MySQL database digunakan untuk menyimpan detail sensor (nama sensor dan lokasi), dan nilai pembacaan sensor (suhu, kelembapan, tekanan).

Let’s get started!!

Things used in this project

  1. ESP32 — DevKitC
  2. BreadBoard
  3. Kabel jumper male-to-male (4 pcs)
  4. Sensor BME-280 (1 pcs)
  5. Kabel USB micro-B
  6. Laptop (with Arduino IDE)
  7. Web hosting with PHP and MySQL database

Note :

  • Web hosting digunakan untuk membuat webpage dengan hosting server dengan domain name. Sebelum memulai eksperimen, pastikan sudah terdaftar pada suatu host service yang dapat diimplementasi dengan PHP dan MySQL, baik yang berbayar atau yang gratis.
  • Pada project ini, digunakan host service 000webhost.com yang bisa dipakai secara gratis.

Web Host Setting

Pada host service yang sudah terdaftar, setting akun hosting dan domain name sesuai dengan keinginan. Domain yang digunakan pada project ini adalah esp32-weatherstation.000webhostapp.com.

Berikut ini dijelaskan step-by-step web host setting per bagian :

MySQL Database

Bagian ini dilakukan untuk membuat database, username, password dan SQL table.

  1. Masuk ke dashboard setting dari website yang akan dibuat.

2. Pilih Tools>Database Manager. Kemudian pilih +New Database untuk membuat database baru.

3. Masukkan database name, database username, dan password sesuai dengan keinginan. Di project ini dipilih esp_data dan esp_user untuk database name dan database username. Simpan data kredensial berikut karena akan digunakan untuk membangun database connection dengan PHP code. Kemudian pilih create.

4. Ditampilkan database name dan database username yang berhasil dibuat dengan awalan code yang diberikan host service. Kemudian pilih PhpMyAdmin untuk membuat SQL table.

5. Pada sidebar pilih code_esp_data yang sudah dibuat kemudian pilih tab SQL.

6. Masukkan SQL query berikut untuk membuat SQL table.

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
)

Pilih Go untuk mengeksekusi query tersebut.

7. SensorData SQL table berhasil dibuat.

PHP Script : HTTP POST-Insert Data

PHP Script bagian ini digunakan untuk menerima request dari ESP32 dan memasukkan data ke MySQL database yang sudah dibuat.

  1. Pada dashboard setting dari website, pilih Tools>File Manager. Kemudian pilih Upload Files untuk masuk ke File Manager.
  2. Pilih public_html pada sidebar kemudian tekan simbol new file untuk membuat file .php baru.

3. Buat .php file dengan nama post-esp-data.php. Kemudian pilih create.

4. Edit file .php yang baru dibuat (post-esp-data.php) dengan memasukkan kode 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;
}

Sebelum paste kode diatas, edit variabel $dbname, $username dan $password sesuai dengan database name, database username serta password yang sudah dibuat.

// 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";

Kemudian pilih save.

5. Jika URL ini diakses http://weatherstation.000webhostapp.com/post-esp-data.php, akan muncul :

PHP Script : Display Database

  1. Pada File Manager folder public_html, buat lagi .php new file dengan nama esp-data.php

2. Edit file .php yang baru dibuat (esp-data.php) dengan memasukkan kode 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>

Sebelum paste kode diatas, edit variabel $dbname, $username dan $password sesuai dengan database name, database username serta password yang sudah dibuat.

// 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";

3. Jika file .php berhasil di-save, maka ketika URL berikut diakses : http://esp32-weatherstation.000webhostapp.com/esp-data.php akan ditampilkan :

Installing Libraries

Dalam project ini dibutuhkan beberapa library agar seluruh device dapat berjalan. Daftar library yang diperlukan, antara lain :

  • Adafruit Unified Sensor
  • Adafruit BME280 library

Jika ada library yang belum ter-install, proses instalasi dapat mengikuti step berikut,

  1. Buka Arduino IDE.
  2. Pilih Sketch > Include Library > Manage Libraries.
  3. Cari nama library yang belum ter-install pada kolom pencarian, lalu pilih Install.
  4. Setelah seluruh library sudah ter-install, restart Arduino IDE 😃.

Schematic

Diagram Skema Projek ESP32 Database

Jika seluruh komponen sudah tersedia, sistem dapat dirancang menurut petunjuk gambar di atas. Sensor BME280 disambungkan melalui default I2C GPIO. Detail pin GPIO yang digunakan :

  • GPIO 3V3 : BME280 (VIN)
  • GPIO GND : BME280(GND)
  • GPIO 21 : BME280(SDA)
  • GPIO22 : BME280(SCL)

Program

Sebelum menjalankan program diatas, edit bagian kredensial dan URL dari web page sesuai dengan kredensial network dan URL web page.

// Edit dengan Network kredensial
const char* ssid = "<SSID Wi-Fi>";
const char* password = "<Password Wi-Fi>";
// REPLACE with your Domain name and URL path or IP address with pathconst
char* serverName = "http://esp32-weatherstation.000webhostapp.com/post-esp-data.php";

setup( )

Pada bagian awal diinisialisasi koneksi jaringan dengan Wi-Fi. Jika WiFi berhasil terhubung, akan tercetak pesan “Connected to WiFi network with IP Address: ” dan IP Address yang digunakan ke serial monitor.

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());

Kode porgram selanjutnya digunakan untuk menginisialisasi sensor BME280 sekaligus checking apakah sensor terdeteksi atau tidak.

// inisialisasi BME280 sensor
bool status = bme.begin(0x76);
if (!status) {
Serial.println("Could not find a valid BME280 sensor, check wiring or change I2C address!");
while (1);
}

Apabila sensor tidak terdeteksi, akan tercetak pesan “Could not find a valid BME280 sensor, check wiring or change I2C address!” pada serial monitor.

loop( )

Pada bagian loop(), program digunakan untuk mengirimkan HTTP POST request setiap 10 sekon terhadap nilai bacaan BME280.

//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(bme.readTemperature()) + "&value2=" + String(bme.readHumidity()) + "&value3=" + String(bme.readPressure()/100.0F) + "";
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 10 seconds
delay(10000);

Result

Setelah kode program selesai di-upload, device berhasil berjalan sesuai dengan spesifikasi program yang diberikan 😃.

Berikut tampilan Arduino IDE Serial Monitor jika semua kondisi sistem berjalan dengan baik :

Tampilan Serial Monitor

Jika domain URL berikut dibuka :

http://esp32-weatherstation.000webhostapp.com/esp-data.php

Akan ditampilkan detail dari bacaan dari sensor BME280 yang disimpan dalam MySQL database. Refresh untuk mendapatkan nilai bacaan terbaru.

Tampilan Web Page

Overall, sistem ESP32 dapat berjalan sesuai dengan program yang di-upload. Sistem mampu untuk mengirimkan HTTP POST request melalui PHP script pada MySQL database untuk memasukkan nilai bacaan sensor BME280. Web page digunakan untuk menampilkan detail data yang disimpan dalam database server.

Detail attribut dalam pada database :

  • ID : nomor id data (unik)
  • Sensor : nama sensor
  • Location : nama lokasi
  • Value 1 : data temperature
  • Value 2 : data humidity
  • Value 3 : data pressure
  • Timestamp : waktu data dimasukkan

Thanks for reading
See you on another ep! 😄

--

--