Báo cáo Bài tập 4 (Bài tập 4) - Nguyễn Hà Sơn

UN
Uni24h
0 lượt tải
3
0

Nội dung tài liệu

Trang 1

Báo cáo Bài tập 4 Họ và tên: Nguyễn Hà Sơn MSSV: 20252120M 1. Code của chương trình #include <DHT.h> #include <LiquidCrystal_I2C.h> #include <Wire.h> // --- Định nghĩa chân kế&t nố&i --- #define DHT_PIN 15 // Chân GPIO 15 cho DHT22 #define PIR_PIN 12 // Chân GPIO 12 cho PIR Motion Sensor #define LED_PIN 32 // Chân GPIO 32 cho LED // --- Câ&u hình Ca7m biế&n DHT --- #define DHT_TYPE DHT22 DHT dht(DHT_PIN, DHT_TYPE); // --- Câ&u hình Màn hình LCD I2C --- // Địa chỉ7 I2C phố7biế&n là 0x27 hoặc 0x3F. LiquidCrystal_I2C lcd(0x27, 16, 2); // --- Câ&u hình thời gian đọc DHT --- const long readInterval = 2000; // Đọc dữ liệu 2 giây/lâOn unsigned long previousMillis = 0; // --- Setup --- void setup() { Serial.begin(115200); Serial.println("--- Bài 4: Thu thập dữ liệu ESP32 Sensors (Setup moi) ---"); // Kh7ởi tạo các chân I/O pinMode(PIR_PIN, INPUT); pinMode(LED_PIN, OUTPUT); // Kh7ởi tạo ca7m biế&n DHT dht.begin(); // Kh7ởi tạo và làm sạch LCD lcd.init(); lcd.backlight(); lcd.clear(); lcd.setCursor(0, 0); lcd.print("System Ready..."); }

Trang 2

// --- Loop --- void loop() { unsigned long currentMillis = millis(); // 1. Đọc dữ liệu DHT định kỳ if (currentMillis - previousMillis >= readInterval) { previousMillis = currentMillis; // Đọc nhiệt độ và độ â7m float humidity = dht.readHumidity(); float temperature = dht.readTemperature(); // Kiế7m tra dữ liệu hợp lệ if (isnan(humidity) || isnan(temperature)) { Serial.println("DHT Data | Failed to read from DHT sensor!"); // Log lốai lcd.setCursor(0, 0); lcd.print("Temp: Read Error!"); lcd.setCursor(0, 1); lcd.print("Humidity: Error!"); } else { // Hiế7n thị lến LCD (16x2) lcd.setCursor(0, 0); lcd.print("Temp: "); lcd.print(temperature, 1); lcd.print((char)223); // Ký tự độ lcd.print("C "); lcd.setCursor(0, 1); lcd.print("Humidity: "); lcd.print(humidity, 1); lcd.print("% "); // Gử7i log dữ liệu qua Serial Serial.print("DHT Data | Temp: "); Serial.print(temperature); Serial.print((char)248); Serial.print("C, Humidity: "); Serial.print(humidity); Serial.println("%"); } } // 2. Đọc trạng thái PIR và điếOu khiế7n LED int motionState = digitalRead(PIR_PIN); if (motionState == HIGH) { // Có chuyế7n động digitalWrite(LED_PIN, HIGH); // Bật LED on Serial.println("PIR | MOTION DETECTED! LED ON."); // Gử7i thống báo

Trang 3

} else { // Khống có chuyế7n động digitalWrite(LED_PIN, LOW); // Tắ&t LED off } delay(10); } 2. Hình ảnh mô phỏng Hình 1: Hình ảnh mô phỏng 3. Link bài tập Link bài tập trên wokwi

Hiển thị 3 trang đầu. Tải tài liệu để xem đầy đủ.

Bình luận (0)

Đăng nhập để tham gia bình luận

Chưa có bình luận nào. Hãy là người đầu tiên!