Project #10 ESP32 - Web Hosting MYSQL


Halo, apa kabar semuanya? Perkenalkan kembali saya Muhammad Vito Ibrahim. Pada kesempatan kali ini saya akan mencoba memasukkan data ke database SQL dengan menggunakan server.

Nah , project kali ini juga merangkap sebagai rekam jejak atau laporan saya untuk mata kuliah ( II2260 Sistem Embedded ). Agar lebih detail kali ini saya akan mencoba menginput data ke MYSQL database dengan ArduinoIDE dan PHP.


Web Hosting MYSQL

Perangkat dan komponen yang digunakan:

1. Mikrokontroler ESP32 Development Board.
2. Arduino IDE.
3. Laptop/Desktop dengan USB port.
4. Kabel micro usb to USB A ( kabel data/charger pada umumnya).
5. Breadboard ( dapat digunakan maupun tidak).
6. Server hosting
7. Script PHP
8. Database MYSQL


Penjelasan beberapa perangkat dan komponen:

1. Mikrokontroler adalah sebuah komputer kecil yang dikemas dalam bentuk chip IC (Integrated Circuit) dan dirancang untuk melakukan tugas atau operasi tertentu.

2. ESP-32 Development Board adalah adalah mikrokontroler chip dengan rangkaian sistem hemat biaya dan rendah daya pada dilengkapi WiFi yang terintegrasi dan Bluetooth.

3. Arduino IDE (Integrated Development Environment) adalah software yang digunakan untuk memprogram di arduino, dengan kata lain Arduino IDE sebagai media untuk memprogram board Arduino. Pada kali ini bisa juga digunakan untuk memprogram mikrokontoler lainnya yaitu ESP32 dengan konfigurasi tambahan.

4. Breadboard adalah papan tempat komponen elektronik tanpa harus disolder.

5. Sensor BMP-180

Langkah pengerjaan :

a. Menyiapkan webhosting

Menggunakan jasa webhosting gratis yaitu 000webhost.com


Melakukan "Sign in" kemudian "+ create new site"

b. Menyiapkan basisdata MYSQL

Memilih  Tools > Database Manager > + New Database



Kemudian memasukan identitas basisdata yang ingin dibuat dan akan melakukan proses "Creating database".




Selanjutnya membuka Manage  > PhpMyAdmin


Membuka Tab Databases dan memastikan bahwa database yang dipilih sudah benar dengan memilih database yang telah dibuat pada tahap sebelumnya.






Dilanjutkan membuka Tab SQL dan memasukkan kueri berikut ini.

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),
 value4 VARCHAR(10),
 value5 VARCHAR(10),
 reading_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)




Jika sudah dilanjutkan dengan menekan tombol GO.



Jika kueri telah dijalankan dan database yang dipilih sudah benar maka akan menampilkan tampilan berikut dan tabel SensorData telah terdapat di dalam basisdata.






c. Menyiapkan script untuk melakukan input data dari ESP32 ke basisdata MYSQL.

Membuka situs files.000webhost.com dan login menggunakan akun yang telah dibuat untuk website di 000webhost pada tahap sebelumnya.

Akan menampilkan seperti berikut.


Selanjutnya klik pada folder public_html dan akan dibuat file index.php di dalamnya

Kemudian membuat file index.php dengan cara memilih create new file dengan simbol seperti yang dilingkari pada gambar di bawah


Lalu masukkan 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;
}
Kemudian mengubah bagian ini menyesuaikan dengan nama database, username database, dan password database yang telah dibuat pada langkah sebelumnya.

Untuk memastikan kode script berjalan, pada panel 000webhost buka Website Settings > General.
Pada bagian tersebut ditampilkan nama website yang telah dihosting. 




Mengakses link website tersebut untuk memastikan bahwa script berjalan lancar sehingga menampilkan tampilan berikut ini.

Jika menampilkan tampilan seperti di atas, maka proses yang dilakukan sudah benar hanya saja tertera "No data posted..." yang artinya belum dilakukan input data apapun.

d. Menampilkan konten database ke website hosting

Pada bagian ini, tabel atau kueri yang telah dibuat di database sebelumnya akan ditampilkan pada website host. 

Pada webhost file manager (https://files.000webhost.com/), buka kembali folder public_html kemudian akan membuat file baru yang bernama esp-data.php yang diisi dengan kode untuk menampilkan database ke website.



Masukkan kode berikut 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>
Dan jangan lupa untuk menyesuaikan bagian berikut seperti pada langkah c.

// Your Database name $dbname = "example_esp_data"; // Your Database user $username = "example_esp_board"; // Your Database user password $password = "YOUR_USER_PASSWORD";

Kemudian buka situs 

nama-domain/esp-data.php

Sesuaikan nama-domain dengan nama pada link website yang dibuat.

Jika semua sesuai maka menampilkan tampilan berikut dan dapat diartikan proses hosting website serta database telah berjalan sukses.

e. Menyiapkan ESP32 dan sensor

Untuk wiring ikuti skema berikut ini





Kemudian pada ArduinoIDE gunakan kode berikut.

/*
  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/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 = "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_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)
  bool status = bme.begin(0x76);
  if (!status) {
    Serial.println("Could not find a valid BME280 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(bme.readTemperature())
                          + "&value2=" + String(bme.readHumidity()) + "&value3=" + String(bme.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 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); 
// Replace with your network credentials
const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
Mengubah bagian tersebut dengan menyesuaikan identitas kredensial jaringan WIFI dan mengubah bagian di bawah ini dengan nama-domain website yang telah dibuat sebelumnya.

const char* serverName = "http://example-domain.com/post-esp-data.php";

Berikut adalah keseluruhan kode yang telah dimodifikasi agar dapat menggunakan sensor BMP180 selain BME280.

// Load Wi-Fi library
#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_BMP085.h>
Adafruit_BMP085 bmp;
// Replace with your network credentials
const char* ssid = "Oko Network";
const char* password = "Oko15101993";
const char* serverName = "http://konekdong.000webhostapp.com//post-esp-data.php";
String apiKeyValue = "tPmAT5Ab3j7F9";
String sensorName = "BMP180";
String sensorLocation = "Office";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0; 
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
void setup() {
 Serial.begin(115200);
 bool status;
// default settings
 // (you can also pass in a Wire library object like &Wire2)
 //status = bmp.begin(); 
 if (!bmp.begin(0x76)) {
 Serial.println("Could not find a valid bmp180 sensor, check wiring!");
 while (1);
 }
// Connect to Wi-Fi network with SSID and password
 Serial.print("Connecting to ");
 Serial.println(ssid);
 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED) {
 delay(500);
 Serial.print(".");
 }



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

 // Print local IP address and start web server
 Serial.println("");
 Serial.println("WiFi connected.");
 Serial.println("IP address: ");
 Serial.println(WiFi.localIP());
 server.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(bmp.readTemperature())
                          + "&value2=" + String(bmp.readSealevelPressure()) + "&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=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);  
}


Jika sudah upload kemudian membuka serial monitor dan atur baud rate ke 115200 kemudian pada ESP32 tekan EN untuk memulai menghubungkan ke jaringan WIFI dan webhost.



Akan menampilkan tampilan seperti berikut.



Kemudian jika membuka link url domain host 

http://example-domain.com/esp-data.php

Seharusnya akan menampilkan tabel data dari database berikut tetapi saya tidak berhasil melakukannya dengan sensor bmp180.


Sehingga pada tampilan website host saya hanya seperti ini

UPDATE :

Berikut adalah kode baru yang saya modifikasi agar dapat berjalan dengan menggunakan sensor BMP180.






// Load Wi-Fi library
#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085.h>

const char* ssid = "Oko Network";
const char* password = "Oko15101993";

const char* serverName = "http://konekdong.000webhostapp.com/post-esp-data.php";

String apiKeyValue = "tPmAT5Ab3j7F9";

String sensorName = "BMP180";
String sensorLocation = "Jakarta";

Adafruit_BMP085 bmp;

void setup() {
 Serial.begin(115200);
 bool status;
// default settings
 // (you can also pass in a Wire library object like &Wire2)
 //status = bmp.begin(); 
 if (!bmp.begin(0x76)) {
 Serial.println("Could not find a valid bmp180 sensor, check wiring!");
 while (1);
 }
// Connect to Wi-Fi network with SSID and password
 Serial.print("Connecting to ");
 Serial.println(ssid);
 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED) {
 delay(500);
 Serial.print(".");
 }
 // Print local IP address and start web server
 Serial.println("");
 Serial.println("WiFi connected.");
 Serial.println("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(bmp.readTemperature())
                          + "&value2=" + String(bmp.readSealevelPressure()) + "&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 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);  

}

Menampilkan tampilan berikut pada webserver hosting






Kompilasi video pengerjaan :


Update




Kesimpulan:

Menampilkan database ke webserver dengan ESP32 MYSQL dan PHP.

Referensi :

1. randomnerdtutorials.com
2. wikipedia


Terimakasih, sampai jumpa pada project berikutnya!



Posting Komentar

0 Komentar