#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd (0x27, 20, 4);
// Siêu âm
int Trig_pin = 18;
int Echo_pin = 19;
long duration;
float Speed_of_sound = 0.034;
float dist_in_cm;
float dist_in_m;
//LDR
#define LIGHT_SENSOR 36
const float GAMMA = 0.7;
const float RL10 = 50;
const char * MQTTServer = "broker.emqx.io";
const char * MQTT_Topic = "TUYEN";
const char * MQTT_ID = "be250242-881a-482a-aff1-be79cc886381";
int Port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
const int ledPin = 5;
#define DHT_TYPE DHT22
#define DHT_PIN 4
DHT dht(DHT_PIN, DHT_TYPE);
void WIFIConnect() {
Serial.println("Connecting to SSID: Wokwi-GUEST");
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected, IP address: ");
Serial.println(WiFi.localIP());
}
void MQTT_Reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect(MQTT_ID)) {
Serial.println("connected");
client.subscribe(MQTT_Topic);
Serial.print("Subscribed to topic: ");
Serial.println(MQTT_Topic);
lcd.setCursor(0, 0);
lcd.print("Topic: ");
lcd.print(MQTT_Topic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
lcd.setCursor(0, 0);
lcd.print("MQTT failed, rc=");
lcd.print(client.state());
delay(5000);
}
}
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.println(topic);
Serial.print("Message: ");
String stMessage;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
stMessage += (char)message[i];
}
Serial.println();
}
void setup() {
Serial.begin(115200);
pinMode(12, OUTPUT);
pinMode(ledPin, OUTPUT);
Serial.println("Starting setup...");
pinMode(Trig_pin, OUTPUT);
pinMode(Echo_pin, INPUT);
WIFIConnect();
client.setServer(MQTTServer, Port);
client.setCallback(callback);
pinMode(ledPin, OUTPUT);
dht.begin();
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Connecting to ");
lcd.setCursor(0, 1);
lcd.print("WiFi ");
lcd.clear();
Serial.println("Setup completed.");
}
void loop() {
delay(10);
if (!client.connected()) {
MQTT_Reconnect();
}
client.loop();
// Đọc dữ liệu từ cảm biến DHT
float t = dht.readTemperature();
float h = dht.readHumidity();
//
digitalWrite(Echo_pin, LOW);
delayMicroseconds(2);
digitalWrite(Trig_pin, HIGH);
delayMicroseconds(10);
digitalWrite(Trig_pin, LOW);
unsigned long duration;
float destance;
duration = pulseIn(Echo_pin,HIGH);
destance = duration * 0.034 /2;
int analogValue = analogRead(LIGHT_SENSOR);
float voltage = analogValue * 5 / 4095.0;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
// Hiển thị thông tin lên LCD
lcd.setCursor(0, 0);
lcd.print("nhietdo: ");
lcd.print(t);
lcd.setCursor(0, 1);
lcd.print("doam: ");
lcd.print(h);
lcd.setCursor(0, 2);
lcd.print("tocdogio: ");
lcd.print(destance);
lcd.setCursor(0, 3);
lcd.print("apsuat: ");
lcd.print(lux);
ndpublish(destance,lux);
delay(2000);
}
void ndpublish(float destance,float lux ) {
float t = dht.readTemperature();
float h = dht.readHumidity();
String nt_da = "{\"nhietdo\":\"" + String(t) + "\",\"doam\":\"" + String(h) + "\",\"tocdogio\":\"" + String(destance) + "\",\"apsuat\":\"" + String(lux) + "\"}";
client.publish(MQTT_Topic, nt_da.c_str());
Serial.print("Published data: ");
Serial.println(nt_da);
}
// <!DOCTYPE html>
// <html lang="en">
// <head>
// <meta charset="UTF-8">
// <meta http-equiv="X-UA-Compatible" content="IE=edge">
// <meta name="viewport" content="width=device-width, initial-scale=1.0">
// <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
// <script src="https://code.jquery.com/jquery-3.6.1.min.js" type="text/javascript"></script>
// <title>Real-time Sensor</title>
// <style>
// .container {
// display: flex;
// justify-content: space-around;
// width: 800px;
// margin: 0 auto;
// }
// .sensor-box {
// border: 1px solid black;
// padding: 20px;
// text-align: center;
// margin: 10px;
// width: 180px;
// }
// .sensor-value {
// font-size: 24px;
// font-weight: bold;
// }
// .temperature { background-color: white; }
// .humidity { background-color: lightgray; }
// .wind-speed { background-color: lightgreen; }
// .pressure { background-color: lightcoral; }
// </style>
// </head>
// <body>
// <h2>Real-time Sensor</h2>
// <div class="container">
// <div class="sensor-box temperature">
// <div id="temperatureValue" class="sensor-value">°C</div>
// <div class="sensor-label">Temperature</div>
// </div>
// <div class="sensor-box humidity">
// <div id="humidityValue" class="sensor-value">% RH</div>
// <div class="sensor-label">Air humidity</div>
// </div>
// <div class="sensor-box wind-speed">
// <div id="windSpeedValue" class="sensor-value">m/s</div>
// <div class="sensor-label">Wind speed</div>
// </div>
// <div class="sensor-box pressure">
// <div id="pressureValue" class="sensor-value">hPa</div>
// <div class="sensor-label">Mean pressure</div>
// </div>
// </div>
// </body>
// </html>
// <script>
// // Khởi tạo MQTT client
// const client = new Paho.MQTT.Client("broker.emqx.io", Number(8083), "be250242-881a-482a-aff1-be79cc886381");
// client.onConnectionLost = onConnectionLost;
// client.onMessageArrived = onMessageArrived;
// // Kết nối MQTT client
// client.connect({onSuccess:onConnect});
// function onConnect() {
// console.log("Connected to broker");
// client.subscribe("TUYEN");
// }
// function onConnectionLost(responseObject) {
// if (responseObject.errorCode !== 0) {
// console.log("onConnectionLost:" + responseObject.errorMessage);
// }
// }
// function onMessageArrived(message) {
// const obj = JSON.parse(message.payloadString);
// // Cập nhật giá trị trên giao diện
// document.getElementById("temperatureValue").innerText = `${obj.nhietdo} °C`;
// document.getElementById("humidityValue").innerText = `${obj.doam}% RH`;
// document.getElementById("windSpeedValue").innerText = `${obj.tocdogio} m/s`;
// document.getElementById("pressureValue").innerText = `${obj.apsuat} hPa`; // Cập nhật áp suất
// }
// </script>
// <!DOCTYPE html>
// <html lang="en">
// <head>
// <meta charset="UTF-8">
// <meta http-equiv="X-UA-Compatible" content="IE=edge">
// <meta name="viewport" content="width=device-width, initial-scale=1.0">
// <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
// <script src="https://code.jquery.com/jquery-3.6.1.min.js" type="text/javascript"></script>
// <title>Real-time Sensor</title>
// <style>
// .container {
// display: flex;
// justify-content: space-around;
// width: 800px; /* Điều chỉnh độ rộng theo ý muốn */
// margin: 0 auto; /* Căn giữa */
// }
// .sensor-box {
// border: 1px solid black;
// padding: 20px;
// text-align: center;
// margin: 10px;
// width: 180px; /* Điều chỉnh độ rộng theo ý muốn */
// }
// .sensor-value {
// font-size: 24px;
// font-weight: bold;
// }
// .temperature { background-color: white; }
// .humidity { background-color: lightgray; }
// .wind-speed { background-color: lightgreen; }
// .pressure { background-color: lightcoral; }
// </style>
// </head>
// <body>
// <h2>Real-time Sensor</h2>
// <div class="container">
// <div class="sensor-box temperature">
// <div id="temperatureValue">°C</div>
// <div class="sensor-label">Temperature</div>
// </div>
// <div class="sensor-box humidity">
// <div id="humidityValue">% RH</div>
// <div class="sensor-label">Air humidity</div>
// </div>
// <div class="sensor-box wind-speed">
// <div id="windSpeedValue">m/s</div>
// <div class="sensor-label">Wind speed</div>
// </div>
// <div class="sensor-box pressure">
// <div id="pressureValue">hPa</div>
// <div class="sensor-label">Mean pressure</div>
// </div>
// </div>
// </body>
// </html>
// <script>
// // Khởi tạo MQTT client
// client = new Paho.MQTT.Client("broker.emqx.io", Number(8083), "be250242-881a-482a-aff1-be79cc886381");
// client.onConnectionLost = onConnectionLost;
// client.onMessageArrived = onMessageArrived;
// // Kết nối MQTT client
// client.connect({onSuccess:onConnect});
// function onConnect() {
// client.subscribe("TUYEN");
// }
// function onConnectionLost(responseObject) {
// if (responseObject.errorCode !== 0) {
// console.log("onConnectionLost:" + responseObject.errorMessage);
// }
// }
// function onMessageArrived(message) {
// const obj = JSON.parse(message.payloadString);
// // Cập nhật giá trị trên giao diện
// document.getElementById("temperatureValue").innerText = `${obj.nhietdo} °C`; // Nhiệt độ
// document.getElementById("humidityValue").innerText = `${obj.doam}% RH`; // Độ ẩm
// document.getElementById("windSpeedValue").innerText = `${obj.tocdogio} m/s`;
// document.getElementById("pressureValue").innerText = `${obj.apsuat} hPa`; // Tốc độ gió
// }
// </script>
// from google.colab import drive
// drive.mount('/content/drive')
// !pip install tensorflow paho-mqtt
// import paho.mqtt.client as mqtt
// import json
// import numpy as np
// import tensorflow as tf
// # Load the pre-trained LSTM model
// model = tf.keras.models.load_model('/content/drive/MyDrive/de3-md2/model/20004247.h5')
// model.summary()
// # Global variable to store sensor data
// sensor_data = []
// # Callback function when a message is received
// def on_message(client, userdata, msg):
// global sensor_data
// try:
// # Decode JSON message
// data = json.loads(msg.payload.decode())
// print("Received data:", data)
// # Append sensor values to the sensor_data list
// sensor_data.append([
// float(data['nhietdo']),
// float(data['doam']),
// float(data['tocdogio']),
// float(data['apsuat'])
// ])
// except Exception as e:
// print("Error decoding JSON:", e)
// # Set up MQTT client and connect to the broker
// client = mqtt.Client()
// client.on_message = on_message
// broker = 'broker.emqx.io'
// port = 1883
// topic = 'TUYEN'
// client.connect(broker, port)
// client.subscribe(topic)
// # Start the MQTT loop to listen for messages
// client.loop_start()
// # Collect data for a certain period (e.g., 10 seconds)
// import time
// time.sleep(10)
// client.loop_stop()
// # Ensure we have enough data
// if len(sensor_data) < 3:
// print("Not enough data received.")
// else:
// # Convert sensor_data to a numpy array
// sensor_data = np.array(sensor_data)
// sensor_data = np.expand_dims(sensor_data, axis=0)
// # Predict the next 3 days
// predicted_values = model.predict(sensor_data)
// # Print the predicted values
// print("Predicted values for the next 3 days:")
// for i, day_values in enumerate(predicted_values[0], start=1):
// print(f"Day {i}: Temperature={day_values[0]}, Humidity={day_values[1]}, Wind Speed={day_values[2]}, Pressure={day_values[3]}")
// QUESTION 1: Use the ESP32 embedded board and connect it to various
// functional modules to fulfill the requirements below?
// DESCRIPTION OF PROJECT AND TASKS
// Use the ESP32 board as the main processing unit for the application.
// Connect the devices and sensors as described in the diagram below?
// a. Use the I2C protocol to connect the ESP32 board to the 20x4 LCD screen?
// b. Connect an LED to the ESP32 board?
// c. Connect the temperature-humidity sensor to the ESP32 board?
// QUESTION 2: Use C++ language and Arduino IDE to implement communication
// functions in the IoT application according to the requirements below?
// DESCRIPTION OF PROJECT AND TASKS
// a. Install necessary libraries to communicate with LCD and MQTT Broker?
// b. Program the ESP32 board to connect to the WIFI network and MQTT Broker?
// Check the status of the Wi-Fi and MQTT Broker connections?
// c. Display the status of Wi-Fi and MQTT Broker on the LCD screen?
// QUESTION 3: Using the ESP32 embedded board and programmed embedded software,
// develop an IoT application that integration an LSTM model to predict sensor values based on the following requirements
// DESCRIPTION OF PROJECT AND TASKS
// a. Embedded programming to read DHT sensor values, simulate values of 2 sensors,
// and use the MQTT protocol to send the received data to the server.
// b. Use Python and the LSTM model to predict sensor values for the next 3 days
// based on the values received from 4 sensors.
// c. Develop a web application that displays the real-time values of the 4 sensors
// and the prediction results from the LSTM model.
// CÂU HỎI 1: Sử dụng bo mạch nhúng ESP32 và kết nối nó với các mô-đun
// chức năng khác nhau để đáp ứng các yêu cầu dưới đây?
// MÔ TẢ DỰ ÁN VÀ NHIỆM VỤ
// Sử dụng bo mạch ESP32 làm bộ xử lý chính cho ứng dụng. Kết nối các thiết bị
// và cảm biến như mô tả trong sơ đồ bên dưới?
// a. Sử dụng giao thức I2C để kết nối bo mạch ESP32 với màn hình LCD 20x4?
// b. Kết nối một đèn LED với bảng ESP32?
// c. Kết nối cảm biến nhiệt độ-độ ẩm với bảng ESP32?
// CÂU HỎI 2: Sử dụng ngôn ngữ C++ và Arduino IDE để thực hiện các chức năng giao tiếp
// trong ứng dụng IoT theo yêu cầu dưới đây?
// MÔ TẢ DỰ ÁN VÀ NHIỆM VỤ
// a. Cài đặt các thư viện cần thiết để giao tiếp với LCD và MQTT Broker?
// b. Lập trình board ESP32 kết nối mạng WIFI và MQTT Broker? Kiểm tra
// trạng thái kết nối Wi-Fi và MQTT Broker?
// c. Hiển thị trạng thái Wi-Fi và MQTT Broker trên màn hình LCD?
// CÂU HỎI 3 : Sử dụng bo mạch nhúng ESP32 và phần mềm nhúng được lập trình,
// phát triển ứng dụng IoT tích hợp mô hình LSTM để dự đoán giá trị cảm biến dựa trên các yêu cầu sau
// MÔ TẢ DỰ ÁN VÀ NHIỆM VỤ
// a. Lập trình nhúng đọc giá trị cảm biến DHT, mô phỏng giá trị của 2 cảm biến
// và sử dụng giao thức MQTT để gửi dữ liệu nhận được về máy chủ.
// b. Sử dụng Python và mô hình LSTM để dự đoán giá trị cảm biến trong 3 ngày tới
// dựa trên giá trị nhận được từ 4 cảm biến.
// c. Phát triển ứng dụng web hiển thị giá trị thời gian thực của 4 cảm biến
// và kết quả dự đoán từ mô hình LSTM.