#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // ที่อยู่ I2C และขนาดจอ LCD
// กำหนดขา Relay
const int relay1Pin = 2; // Relay 1 เชื่อมต่อกับ GPIO 2
const int relay2Pin = 4; // Relay 2 เชื่อมต่อกับ GPIO 4
// ตัวแปรเวลา
unsigned long previousMillis1 = 0;
unsigned long previousMillis2 = 0;
const unsigned long relay1Interval = 30000; // 30 วินาที (เปิด)
const unsigned long relay1OffInterval = 30000; // 30 วินาที (ปิด)
const unsigned long relay2Interval = 60000; // 60 วินาที (เปิด)
const unsigned long relay2OffInterval = 60000; // 60 วินาที (ปิด)
bool relay1State = false;
bool relay2State = false;
void setup() {
// ตั้งค่า LCD
lcd.init();
lcd.backlight();
// แสดงข้อความเริ่มต้น
lcd.setCursor(0, 0);
lcd.print("Initializing...");
delay(2000);
// ตั้งค่าขา Relay เป็น OUTPUT
pinMode(relay1Pin, OUTPUT);
pinMode(relay2Pin, OUTPUT);
digitalWrite(relay1Pin, LOW); // เริ่มต้น Relay 1 ปิด
digitalWrite(relay2Pin, LOW); // เริ่มต้น Relay 2 ปิด
// เริ่มต้น Serial Monitor
Serial.begin(115200);
Serial.println("ระบบควบคุม Relay พร้อมทำงาน");
// แสดงผลการเริ่มต้นเสร็จสิ้น
lcd.clear();
}
void loop() {
// คำนวณเวลาในรูปแบบ MM:SS
unsigned long currentMillis = millis();
unsigned long seconds = currentMillis / 1000;
unsigned long minutes = seconds / 60;
seconds = seconds % 60;
// อัปเดตเวลาแสดงบน LCD
lcd.setCursor(0, 0);
lcd.print("Time: ");
if (minutes < 10) lcd.print("0");
lcd.print(minutes);
lcd.print(":");
if (seconds < 10) lcd.print("0");
lcd.print(seconds);
// ควบคุม Relay 1
if (!relay1State && currentMillis - previousMillis1 >= relay1Interval) {
digitalWrite(relay1Pin, HIGH); // เปิด Relay 1
relay1State = true;
previousMillis1 = currentMillis;
Serial.println("Relay 1 ON");
} else if (relay1State && currentMillis - previousMillis1 >= relay1OffInterval) {
digitalWrite(relay1Pin, LOW); // ปิด Relay 1
relay1State = false;
previousMillis1 = currentMillis;
Serial.println("Relay 1 OFF");
}
// ควบคุม Relay 2
if (!relay2State && currentMillis - previousMillis2 >= relay2Interval) {
digitalWrite(relay2Pin, HIGH); // เปิด Relay 2
relay2State = true;
previousMillis2 = currentMillis;
Serial.println("Relay 2 ON");
} else if (relay2State && currentMillis - previousMillis2 >= relay2OffInterval) {
digitalWrite(relay2Pin, LOW); // ปิด Relay 2
relay2State = false;
previousMillis2 = currentMillis;
Serial.println("Relay 2 OFF");
}
// แสดงสถานะของ Relay บน LCD
lcd.setCursor(0, 1);
lcd.print("R1:");
lcd.print(relay1State ? "ON " : "OFF");
lcd.print(" R2:");
lcd.print(relay2State ? "ON " : "OFF");
delay(500); // หน่วงเวลาเล็กน้อยเพื่ออัปเดตข้อมูล
}