Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

BÁO CÁO THỰC HÀNH

CÔNG NGHỆ IOT VÀ ỨNG DỤNG (KC326)


Buổi 5: Thiết kế Web App giao tiếp Firebase (DHT11, RGB)
Nhóm 06:
STT Họ và tên MSSV Đóng góp
1 Hà Tấn Đạt B2004124 100%
2 Lê Vũ Linh B2004091 100%
3 Trần Phước Tính B2004113 100%
4 Huỳnh Thị Gia Hân B2003510 100%
5 Lê Kim Phương B2011755 100%
6 Nguyễn Trọng Pháp B2011749 100%

1. Nội dung thực hành


Nội dung 1: Tạo tài khoản email cho ứng dụng nhomX_app@myemail.com
(X là số thứ tự nhóm).

Nội dung 2: Cấu hình và tạo Web Apps trên VS Code.


 Firebase: Tạo Web Apps
 VS Code:
+ Đăng nhập Firebase
Nội dung 3: Tạo hai button trên ứng dụng để tạo chức năng Log in và Log
out.
Code HTML
<style>

.login-screen {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.login-form {
display: flex;
flex-direction: column;
gap: 10px;
}
</style>

Code cho màn hình login. Và tạo 1 button login style và body:
<<form class="login-form">

<label for="email">Email:</label>
<input type="email" id="email" required>

<label for="password">Password:</label>
<input type="password" id="password" required>

<button type="submit">Login</button>
</form>
Code JS
document.addEventListener("DOMContentLoaded", function() {
const loginForm = document.querySelector(".login-form");
const loginScreen = document.querySelector(".login-screen");
const mainScreen = document.querySelector(".main-screen");
const logoutButtons = document.querySelectorAll(".logout-button");

loginForm.addEventListener("submit", function(event) {
event.preventDefault();
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;

if (email === "nhom6app@gmail.com" && password === "Nhom6@iot") {


loginScreen.style.display = "none";
mainScreen.style.display = "flex";
} else {
alert("Invalid email or password");
}
});
});

Nội dung 4: Chọn và tạo hai UI hiển thị giá trị nhiệt độ và độ ẩm (Đường
dẫn: NhomX/temperature, NhomX/humidity).
Code ESP
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <DHT.h>

//Provide the token generation process info.


#include "addons/TokenHelper.h"
//Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"

// Insert your network credentials


#define WIFI_SSID "Xuan Dao 1"
#define WIFI_PASSWORD "67896789"

// Insert Firebase project API Key


#define API_KEY "AIzaSyD2SUuyyn37jExw4ieSf8lx7trlAb2HNK4"
// Insert RTDB URLefine the RTDB URL */
#define DATABASE_URL "https://esp32-b65b5-default-
rtdb.firebaseio.com/"

#define DHTPIN 13 // GPIO pin where the DHT11 data pin is connected
#define DHTTYPE DHT11
bool signupOK = false;

DHT dht(DHTPIN, DHTTYPE);


FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

void setup() {
Serial.begin(115200);

WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());

dht.begin();

/* Assign the api key (required) */


config.api_key = API_KEY;

/* Assign the RTDB URL (required) */


config.database_url = DATABASE_URL;

/* Sign up */
if (Firebase.signUp(&config, &auth, "", "")){
Serial.println("ok");
signupOK = true;
}
else{
Serial.printf("%s\n", config.signer.signupError.message.c_str());
}

/* Assign the callback function for the long running token


generation task */
config.token_status_callback = tokenStatusCallback; //see
addons/TokenHelper.h

Firebase.begin(&config, &auth);
Firebase.reconnectWiFi(true);
}

void loop() {
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();

if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read data from DHT sensor");
delay(2000);
return;
}

Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C\t");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");

// Upload data to Firebase Realtime Database


Firebase.RTDB.setString(&fbdo, "/Temperature", String(temperature));
Firebase.RTDB.setString(&fbdo, "/Humidity", String(humidity));

delay(10000); // Update data every minute


}
Mạch thực tế:
Code HTML
<h1>Firebase ESP32</h1>
<p>Humidity: <span id="humidity"></span></p>
<p>Temperature: <span id="temperature"></span></p>

Code JS
var datatemperature = 'Nhom6/temperature';
var datahumidity = 'Nhom6/humidity';
const databaseFloat = database.ref(datatemperature);
const databaseInt = database.ref(datahumidity);

var temperature;
var humidity;
databaseFloat.on('value', (snapshot) => {
temperature = snapshot.val();
console.log(temperature);
document.getElementById("Temperature").innerHTML = temperature;
}, (errorObject) => {
console.log('The read failed: ' + errorObject.name);
});

databaseInt.on('value', (snapshot) => {


humidity = snapshot.val();
console.log(humidity);
document.getElementById("Humidity").innerHTML = humidity;
}, (errorObject) => {
console.log('The read failed: ' + errorObject.name);
});
Nội dung 5: Tạo bảng hiển thị giá trị hai mảng nhiệt độ và độ ẩm trên Web
App (Đường dẫn: NhomX/temperature_arr, NhomX/humidity_arr).
Code HTML
<div class="main-screen">
<h2>Bảng dữ liệu nhiệt độ và độ ẩm</h2>
<table>
<tr>
<th>STT</th>
<th>Nhiệt độ</th>
<th>Độ ẩm</th>
</tr>
<tbody id="dataBody">
</tbody>
</table>
</div>
Code CSS
.main-screen table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
}
h2{
display: flex;
align-items: center;
justify-content: center;
height: 10vh;
margin: 0;
color: #74a4f2
}
.main-screen th,
.main-screen td {
padding: 8px;
text-align: left;
border-bottom: 1px #74a4f2;
}

.main-screen th {
background-color: gray
;
}

.main-screen tbody tr:nth-child(even) {


background-color: white
;
}

.main-screen tbody tr:hover {


background-color: #86849c;
}

Code JS
database.ref("Nhom6/temperature_arr").once("value", function(snapshot) {
var temperatureData = snapshot.val();
var tableBody = document.getElementById("dataBody");

while (tableBody.firstChild) {
tableBody.removeChild(tableBody.firstChild);
}

for (var i = 0; i < temperatureData.length; i++) {


var row = document.createElement("tr");
var indexCell = document.createElement("td");
var temperatureCell = document.createElement("td");

indexCell.textContent = i + 1;
temperatureCell.textContent = temperatureData[i];

row.appendChild(indexCell);
row.appendChild(temperatureCell);
tableBody.appendChild(row);
}
});
database.ref("Nhom6/humidity_arr").once("value", function(snapshot) {
var humidityData = snapshot.val();
var tableBody = document.getElementById("dataBody");
var rows = tableBody.getElementsByTagName("tr");
for (var i = 0; i < humidityData.length; i++) {
var humidityCell = document.createElement("td");
humidityCell.textContent = humidityData[i];
rows[i].appendChild(humidityCell);
}
});
Nội dung 6: Thêm UI tính và hiển thị giá trị trung bình của nhiệt độ và độ
ẩm.
Code JS
const temperatureRef = firebase.database().ref("Nhom6/temperature_arr");
temperatureRef.once("value", function(snapshot) {
const temperatureData = snapshot.val();
let totalTemperature = 0;

for (let i = 0; i < temperatureData.length; i++) {


totalTemperature += temperatureData[i];
}

const averageTemperature = totalTemperature / temperatureData.length;


const roundedAverageTemperature = averageTemperature.toFixed(2);
temperatureElement.textContent = + roundedAverageTemperature;
});

const humidityRef = firebase.database().ref("Nhom6/humidity_arr");


humidityRef.once("value", function(snapshot) {
const humidityData = snapshot.val();
let totalHumidity = 0;

for (let i = 0; i < humidityData.length; i++) {


totalHumidity += humidityData[i];
}

const averageHumidity = totalHumidity / humidityData.length;


const roundedAverageHumidity = averageHumidity.toFixed(2);
humidityElement.textContent = + roundedAverageHumidity;
});

Nội dung 7: Thêm UI để thêm tính năng cảnh báo khi nhiệt độ vượt một giá
trị đặt (giá trị đặt được thiết lập ngay trên ứng dụng).

Code JS
databaseFloat.on('value', (snapshot) => {
temperature = snapshot.val();
console.log(temperature);
document.getElementById("temperature").innerHTML = temperature;

if (temperature > 30) {


alert('Nhiệt độ vượt quá mức quy định');
}
}, (errorObject) => {
console.log('The read failed: ' + errorObject.name);
});

You might also like