#include <DHT.h>
#include <Servo.h>
#include <TimeLib.h>
#include <Wire.h>
#include <RTClib.h>
#define buttonPin 3
#define dhtPin 2
#define dhtType DHT22
#define ldrPin A2
DHT dht(dhtPin, dhtType);
RTC_DS1307 rtc; //khai bao rtc
//khai bao khoa
Servo servo;
int pos = 0;
bool buttonState = false;
void setup() {
Serial.begin(9600);
//khoi dong rtc
if (!rtc.begin()) {
Serial.println("Không tìm thấy RTC");
}
if (!rtc.isrunning()) {
Serial.println("RTC không chạy, khởi tạo thời gian ...");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
dht.begin();
servo.attach(9);
servo.write(0); //khoá đóng
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
int ldrValue = analogRead(ldrPin);
float temperature = dht.readTemperature();
buttonState = digitalRead(buttonPin);
DateTime now = rtc.now();
Serial.print("Thời gian: ");
getTime();
Serial.print("Ánh sáng: ");
Serial.println(ldrValue);
Serial.print("Nhiệt độ: ");
Serial.println(temperature);
if (buttonState == LOW) {
openLock();
delay(200);//tránh mở khoá liên tiếp
}
// else if (ldrValue > 300 && temperature > 25) {
// openLock();
// }
if (now.hour() >= 8 && now.hour() <= 18) {
if (ldrValue > 300 && temperature > 25) {
openLock();
}
}
delay(3000);
}
void openLock(){
Serial.print("Khoá mở lúc: ");
getTime();
for (pos = 0; pos <= 90; pos +=1) {
servo.write(pos);
delay(15);
}
delay(5000);// open 5s
for (pos = 90; pos >= 0; pos -= 1) {
servo.write(pos);
delay(15);
}
}
void getTime() {
DateTime now = rtc.now();
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.println(now.second(), DEC);
}