วันพุธที่ 1 เมษายน พ.ศ. 2563

โปรเจค IoT ESP8266 วัดอุณหภูมิความชื้น บันทึกลงดาต้าเบส MySQL



เป้าหมายของโปรเจคนี้คือเราต้องดูข้อมูลด้วยการเข้าถึงโดเมน ของเราเอง ไม่ว่าจะอยู่ส่วนไหนของโลก โดย ESP8266 จะสร้างไคลเอ็นต์  ที่ทำให้คำขอ HTTP POST ไปยังสคริปต์ PHP เพื่อแทรกข้อมูล (การอ่านเซ็นเซอร์) ลงในฐานข้อมูล MySQL

โดยบทความนี้จะแสดงการส่งข้อมูลจาก ESP8266 ไปเก็บในฐานข้อมูล MySQLโดยใช้ เซนเซอร์ BME280  วัดอุณหภูมิความชื้น เชื่อมต่อกับ ESP8266 และเชื่อมต่อกับ WiFi ออก อินเตอร์เน็ต ทำให้เราสามารถดูข้อมูลจากที่ไหนก็ได้ที่มี อินเตอร์เน็ต และยังนำข้อมูลย้อนหลังไปวิเคราะห์ได้ด้วย



1. จด Domain Name และ  Hosting

 จด Domain Name และ  Hosting เพื่อเรียกใช้เว็บแอพพลิเคชั่น PHP  และ ฐานข้อมูล MySQL โดยในตัวอย่างเลือกใช้ Hosting ของ appservhosting.com





2. เตรียมฐานข้อมูล MySQL


เข้าใช้งาน Hosting ตาม appservhosting แจ้งข้อมูล ผ่านทาง Email มา ในตัวอย่างเป็น http://ns33.appservhosting.com/vhcs2





ไปที่ Manage SQL





ไปที่ Add SQL Database




ที่ Database name ตั้งชื่อเป็น esp_data -> Add




ไปที่ Add SQL user




ที่ SQL user name เป็น esp_board และ Password ตามต้องการ -> Add




ถ้าสำเร็จ จะแสดง SQL user successfully added!




ไปที่ PhpMyAdmin




 Username เป็น esp_board และ Password ตามที่ได้สร้างไว้ก่อนหน้านี้ -> Go



ไปที่ esp_board





ไปที่ SQL





คัดลอก SQL query ด้านล่างไปวางในกรอบสีแดง แล้วกด “Go":

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
)



 หลังจากนั้นต้องเห็นตารางที่สร้างขึ้นใหม่ชื่อ SensorData ในฐานข้อมูล





3. สร้าง FTP Accounts 


สำหรับใช้ Upload ไฟล์ ไปยังโฮส


ไปที่ Email Accounts




ไปที่ Add mail users




ที่ Username เป็น info และ Password ตามต้องการ -> Add




จะพบ mail users ที่สร้างขึ้น



ไปที่ FTP Accounts




ไปที่ Add FTP user





ที่ Username เป็น info และ Password ตามต้องการ -> Add




ถ้าสำเร็จ จะแสดง FTP account added!






4. สร้างสคริปต์ PHP ไฟล์ที่ 1


ที่มีหน้าที่ในการรับคำขอขาเข้าจาก ESP8266 และแทรกข้อมูลลงในฐานข้อมูล MySQL


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


เปิดโปรแกรม สำหรับเขียนเว็บ เช่น Notepad หรือโปรแกรมอื่นๆ แล้ว คัดลอกโค๊ดไปวาง




นำข้อมูลที่ได้จากขั้นตอนที่ 2 มาแก้ไข สคริปต์ PHP 3 ค่า คือ $dbname, $username และ $password

$dbname = "esp_data";
$username = "esp_board";
$password = "รหัสผ่าน";




ไปที่ File -> Save As...




ตั้งชื่อไฟล์ เป็น post-esp-data.php -> Save





5. อัพโหลดไฟล์ จากคอมพิวเตอร์ ไปยัง Hosting
.

ดาวน์โหลด FileZilla Client และติดตั้ง


Download FileZilla Client for Windows (64bit)


เปิดใช้งาน FileZilla Client




ฝั่ง Hosting : คลิกไปที่ โฟลเดอร์ htdocs




ฝั่ง คอมพิวเตอร์ PC : คลิกเลือกไฟล์ post-esp-data.php แล้วคลิกขวา -> Upload




ถ้าสำเร็จ ไฟล์ post-esp-data.php จะอัพโหลดไปยัง Hosting





6. ทดสอบการทำงานของสคริปต์ PHP ไฟล์ที่ 1
.

เปิดเว็บบราวเซอร์ ที่ URL ป้อน

โดเมนเนมที่จดมา.com/post-esp-data.php



ถ้าสำเร็จ จะแสดง No data posted with HTTP POST.





7. สร้างสคริปต์ PHP ไฟล์ที่ 2


ที่มีหน้าที่ในการ นำข้อมูลมาแสดงผล


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


เปิดโปรแกรม สำหรับเขียนเว็บ เช่น Notepad หรือโปรแกรมอื่นๆ แล้ว คัดลอกโค๊ดไปวาง จากนั้น นำข้อมูลที่ได้จากขั้นตอนที่ 2 มาแก้ไข สคริปต์ PHP 3 ค่า คือ $dbname, $username และ $password

$dbname = "esp_data";
$username = "esp_board";
$password = "รหัสผ่าน";

.



ไปที่ File -> Save As...

ตั้งชื่อไฟล์ เป็น esp-data.php -> Save




อัพโหลดไฟล์ esp-data.php  จากคอมพิวเตอร์ ไปยัง Hosting





เปิดเว็บบราวเซอร์ ที่ URL ป้อน

โดเมนเนมที่จดมา.com/esp-data.php



ถ้าสำเร็จ จะแสดง

ID Sensor Location Value 1 Value 2 Value 3 Timestamp





8. ทดสอบ ESP8266 และ BME280


ต่อวงจร และ ทดสอบการทำงาน ตามบทความด้านล่าง


โปรเจค IoT ESP8266 NodeMCU วัดอุณหภูมิ ด้วย BME280



9. อัพโหลดโค้ดของ ESP8266 


เปิด 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/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);  
}




ก่อนการอัพโหลดต้องแก้ไขโค้ด ตามเครือข่าย WiFi ที่เลือกใช้งาน และ โดเมนเนมที่จดมา

const char* ssid     = "REPLACE_WITH_YOUR_SSID"; // คือ ชื่อWiFiที่ต้องการเชื่อมต่อ
const char* password = "REPLACE_WITH_YOUR_PASSWORD"; // คือ รหัสผ่าน

const char* serverName = "http://example.com/post-esp-data.php"; // โดเมนเนมที่จดมา.com/post-esp-data.php


ตรวจความถูกต้องแบบละเอียด เช่น...ตัวพิมพ์เล็ก , ตัวพิมพ์ใหญ่ อักขระต่างๆ ให้ถูกต้อง



อัพโหลดโค้ดที่แก้ไขแล้ว


เลือกชนิดของบอร์ด : ไปที่ Tools > Board : เลือกเป็น NodeMCU 0.9 (ESP-12 Module)





เลือกพอร์ตการใช้งาน : ไปที่ Tools > Port แล้วเลือกพอร์ตที่ปรากฏ ในตัวอย่างเลือกเป็น "COM12"





กดปุ่ม    เพื่ออัพโหลด 





หากสามารถอัพโหลดโปรแกรมลงบอร์ดได้สำเร็จ จะแสดงคำว่า Done uploading. ที่แถบด้านล่าง





10. ทดสอบการทำงานของโปรเจค



เปิดเว็บบราวเซอร์ ที่ URL ป้อน


โดเมนเนมที่จดมา.com/esp-data.php



ถ้าสำเร็จ ที่หน้าจอจะแสดง อุณหภูมิ (Temperature) ความชื้นสัมพัทธ์ (Humidity) ความกดอากาศ  (Pressure) ตามรูปด้านล่าง






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

โปรเจค IoT ESP8266 วัดอุณหภูมิความชื้น บันทึกลงดาต้าเบส MySQL

เป้าหมายของโปรเจคนี้คือเราต้องดูข้อมูลด้วยการเข้าถึงโดเมน ของเราเอง ไม่ว่าจะอยู่ส่วนไหนของโลก โดย ESP8266 จะสร้างไคลเอ็นต์  ที่ทำให้คำขอ...