#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int pirPin = 13; // ขา PIR Sensor (ใช้ขาที่เหมาะสมสำหรับ ESP32)
const int lightPin = 34; // ขา LDR Sensor (ใช้ขาที่เหมาะสมสำหรับ ESP32)
const int ledPin = 12; // ขา LED (ใช้ขาที่เหมาะสมสำหรับ ESP32)
bool ledStatus = false; // สถานะของ LED
bool errorState = false; // สถานะของ Error
int lightLevel = 0; // ระดับความสว่างของหลอดไฟ
bool motionDetected = false; // ตรวจสอบการเคลื่อนไหว
LiquidCrystal_I2C lcd(0x27, 16, 2); // กำหนดที่อยู่ของ LCD (0x27 หรือ 0x3F ขึ้นอยู่กับโมดูลที่ใช้)
void setup() {
Serial.begin(115200); // สำหรับ ESP32 ใช้ 115200 baud rate
pinMode(pirPin, INPUT);
pinMode(lightPin, INPUT);
pinMode(ledPin, OUTPUT);
lcd.init(); // เริ่มต้นการทำงานของ LCD
lcd.backlight(); // เปิดแสงไฟหลังจอ
lcd.setCursor(0, 0);
lcd.print("Smart Street");
}
void loop() {
// ตรวจสอบการเคลื่อนไหว
motionDetected = digitalRead(pirPin);
if (motionDetected && !errorState) { // เปิดไฟเฉพาะเมื่อไม่อยู่ในสถานะ Error
if (!ledStatus || analogRead(ledPin) != 255) {
analogWrite(ledPin, 255); // ตั้งค่า LED ที่ 100%
ledStatus = true;
if (!errorState) { // แสดงข้อความ LED: 100% ถ้าไม่อยู่ในสถานะ Error
lcd.clear();
lcd.print("LED: 100%");
}
}
} else if (!errorState) { // ปรับแสงไฟเมื่อไม่อยู่ในสถานะ Error
if (ledStatus || analogRead(ledPin) != 128) {
analogWrite(ledPin, 128); // ตั้งค่า LED ที่ 50%
ledStatus = false;
if (!errorState) { // แสดงข้อความ LED: 50% ถ้าไม่อยู่ในสถานะ Error
lcd.clear();
lcd.print("LED: 50%");
}
}
}
// ตรวจสอบสถานะของหลอดไฟ
lightLevel = analogRead(lightPin);
Serial.println(lightLevel); // แสดงค่าความสว่างใน Serial Monitor
if (lightLevel > 950) { // กำหนดค่าตามความเหมาะสม
if (!errorState) {
errorState = true;
lcd.clear();
lcd.print("Error LED");
analogWrite(ledPin, 0); // ปิดไฟ LED
ledStatus = false;
}
Serial.println("Light failure detected, maintenance required.");
} else {
if (errorState) {
errorState = false;
lcd.clear();
if (ledStatus) {
lcd.print("LED: 100%");
} else {
lcd.print("LED: 50%");
}
}
}
delay(1000);
}