Home Internet of Things - IoT ESP8266/ESP32 và Raspberry Pi LAMP Server – [Bài 4]: ESP8266/ESP32 đọc dữ liệu cảm biến và gửi lên Server

ESP8266/ESP32 và Raspberry Pi LAMP Server – [Bài 4]: ESP8266/ESP32 đọc dữ liệu cảm biến và gửi lên Server

by Khanh Tran

Dự án này chúng ta có thể sử dụng với cả ESP32 và ESP8266. Bạn chỉ cần thiết kế một mạch đơn giản sau đó đọc và gửi nhiệt độ, độ ẩm, áp suất và bât kì dữ liệu nào khác vào cơ sở dữ liệu của bạn sau mỗi 30 giây.

1. Chuẩn bị linh kiện

Trong ví dụ này, chúng tôi sẽ sử dụng cảm biến BME280. Dưới đây là danh sách các linh kiện bạn cần để thiết kế phần cứng cho dự án này:

2. Schematics

Mô-đun cảm biến BME280 tôi sử dụng giao tiếp qua giao thức I2C, vì vậy bạn cần kết nối nó với các chân I2C của ESP32 hoặc ESP8266.

Cách BME280 kết nối với ESP32:

  • GPIO 22:  SCL (SCK)
  • GPIO 21:  SDA (SDI)
Hình 1: kết nối BME280 với ESP32

Cách BME280 kết nối với ESP8266:

Các chân I2C của ESP8266 là:

  • GPIO 5  (D1): SCL (SCK)
  • GPIO 4  (D2): SDA (SDI)
Hình 2: kết nối BME280 với ESP8266

3. Lập trình cho ESP32 / ESP8266

Chúng tôi lập trình ESP32/ESP8266 bằng Arduino IDE, vì vậy bạn phải cài đặt tiện ích bổ sung ESP32/ESP8266 trong Arduino IDE của bạn.

Sau khi cài đặt các thư viện cần thiết, hãy sao chép đoạn code sau vào Arduino IDE của bạn, nhưng chưa tiến hành nạp code. Bạn cần thực hiện một số thay đổi để làm nó hoạt động.

/*
  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);  
}

Cài đặt thông tin mạng:

Bạn cần sửa đổi SSID và password theo wifi mà bạn muốn kết nối.

// Replace with your network credentials
const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Setting serverName của bạn:

Bạn cần nhập địa chỉ IP của Raspberry Pi, để ESP8266 có thể gửi data lên LAMP Server.

const char* serverName = "http://Your-Raspberry-Pi-IP-Address/post-esp-data.php";

Ví dụ:

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

Bây giờ, bạn có thể nạp code cho esp8266. Nó sẽ hoạt động cho cả ESP32 và ESP8266.

Giải thích cơ bản cách hoặt động của đoạn code trên:

Dự án này đã khá dài, vì vậy tôi sẽ không đề cập chi tiết về cách thức hoạt động của code, nhưng có thể tóm tắt nhanh:

  • Import tất cả các thư viện mà dự án cần (nhập các thư viện ESP32 hoặc ESP8266 dựa trên bảng đã chọn trong Arduino IDE).
  • Đặt các biến (apiKeyValue, sensorName, sensorLocation).
  • Các apiKeyValue chỉ là một chuỗi ngẫu nhiên mà bạn có thể sửa đổi. Nó được sử dụng vì lý do bảo mật, vì vậy chỉ những ai biết API key của bạn mới có thể publish data lên database.
  • Khởi tạo giao tiếp nối tiếp để gỡ lỗi.
  • Thiết lập kết nối Wi-Fi với bộ định tuyến của bạn.
  • Khởi tạo BME280 để nhận dữ liệu cảm biến.

Sau đó, trong hàm loop() là nơi bạn gọi HTTP POST request, cứ sau 30 giây gửi các dữ liệu mới nhất từ BME280:

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

int httpResponseCode = http.POST(httpRequestData);

4. Kết quả

Sau khi hoàn thành tất cả các bước. Nếu mọi thứ đều chính xác, đây là những gì bạn sẽ thấy trong Màn hình Serial của Arduino IDE:

Hình 3: dự liệu trên màn hình Serial của Arduino IDE

Nếu bạn mở trình duyệt của Raspberry Pi theo URL: http://Your-Raspberry-Pi-IP-Address/esp-data.php. Bạn sẽ thấy data được lưu trữ trong database của bạn.  Refresh trang web để xem các dữ liệu mới nhất:

Hình 4: dự liệu trên trình duyệt của Raspberry Pi

Bạn cũng có thể truy cập phpMyAdmin để quản lý dữ liệu được lưu trữ trong bảng SensorData. Có thể xóa, chỉnh sửa, ….

Hình 5: dự liệu trên phpMyAdmin

Kết thúc

Trong hướng dẫn này, bạn đã học cách xuất dữ liệu cảm biến vào cơ sở dữ liệu trong Raspberry Pi LAMP Server.

Ví dụ được cung cấp càng đơn giản càng tốt để bạn có thể hiểu mọi thứ hoạt động như thế nào. Sau khi hiểu ví dụ này, bạn có thể thay đổi giao diện trang web, xuất dữ liệu cảm biến khác, đọc và gửi dữ liệu từ nhiều thiết bị ESP khác, hay có thể cải thiện để không chỉ đọc trong mạng local mà có thể đọc trên internet.

You may also like

2 comments

khoa 19 June, 2020 - 9:42 pm

làm cách nào để biết apiKeyValue a

Reply
Khanh Tran 23 June, 2020 - 1:06 am Reply

Leave a Comment