#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define TRIG_PIN 4
#define ECHO_PIN 2
#define SWITCH_PIN 19 // Chân kết nối công tắc
LiquidCrystal_I2C lcd(0x3F, 20, 4); // Địa chỉ I2C của LCD
bool wateringMode = false; // Trạng thái chế độ tưới tiêu
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(SWITCH_PIN, INPUT_PULLUP); // Cài đặt công tắc ở chế độ INPUT_PULLUP
lcd.init();
lcd.backlight();
displayInitialScreen();
}
void loop() {
handleIrrigationSystem();
}
void displayInitialScreen() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("He thong tuoi tieu");
}
void displayIrrigationMode(bool mode) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Che do tuoi tieu:");
lcd.setCursor(0, 1);
lcd.print(mode ? "On" : "Off");
}
long measureDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
long distance = duration * 0.034 / 2; // Tính khoảng cách (cm)
return distance;
}
void displayWateringData() {
long distance = measureDistance();
lcd.setCursor(0, 1);
lcd.print("On ");
lcd.setCursor(0, 2);
lcd.print("Luong nuoc tuoi: ");
lcd.setCursor(0, 3);
lcd.print(distance);
lcd.print(" cm ");
}
bool debounceSwitch(int pin) {
static bool lastState = HIGH; // Trạng thái trước đó của công tắc
static unsigned long lastDebounceTime = 0; // Thời điểm trạng thái cuối cùng được ghi nhận
const unsigned long debounceDelay = 50; // Thời gian debounce (50ms)
bool currentState = digitalRead(pin);
if (currentState != lastState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
lastState = currentState;
}
return lastState == LOW;
}
void handleIrrigationSystem() {
static bool lastWateringMode = false; // Trạng thái trước đó
int switchState = digitalRead(SWITCH_PIN); // Đọc trạng thái công tắc
wateringMode = (switchState == LOW); // Công tắc bật (LOW)
if (wateringMode != lastWateringMode) { // Chỉ cập nhật khi có thay đổi
lastWateringMode = wateringMode;
if (wateringMode) {
displayIrrigationMode(true);
} else {
displayIrrigationMode(false);
}
}
if (wateringMode) {
displayWateringData();
delay(500);
} else {
delay(2000);
}
}