#include "RTClib.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int cdong = 33;
const int led = 27;
const int loa = 4;
int value=0;
int state=LOW;
RTC_DS1307 rtc;
LiquidCrystal_I2C lcd(0x27,16,2);
char daysOfTheWeek[7][12] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};// mang ki tu chua cac ngay trong tuan
void setup() {
lcd.init();//khoi dong man hinh lcd
lcd.backlight();//bat den nen
pinMode(cdong,INPUT);
pinMode(led,OUTPUT);
pinMode(loa,OUTPUT);
Serial.begin(9600);
if (! rtc.begin())//rtc.begin la khoi tao de ket noi module
{
Serial.print("Couldn't find RTC");
while (1);
}
if (! rtc.isrunning())//rtc.isrunning la doc cac thanh ghi ben trong ds1307
//ham kiem tra module co tra ve thoi gian k
{
Serial.print("RTC is NOT running!");
Serial.println();
}
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));// rtc.adjust la ham dat tg ngày va giờ // datetime(...) là tự động đặt tg theo máy tính
//rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); // hàm này giúp tự thiết lập thời gian
}
void loop() {
value=analogRead(cdong);// doc dien ap ow chan A0 (tra ve 1 so nguyen tuwf 0-1028)
DateTime now = rtc.now();//rtc.now trả về ngày và giờ hiện tại và thg lưu trong biến DateTime
if(value>100){
digitalWrite(led,HIGH);
digitalWrite(loa,HIGH);
if(state==LOW){
lcd.setCursor(1,0);
lcd.print("!!! CANH BAO KHAN CAP !!!");
lcd.setCursor(1,1);
lcd.print("Phat hien chuyen dong ");
delay(300);
state=HIGH;
}
}
else{
digitalWrite(led,LOW);
digitalWrite(loa,LOW);
if(state==HIGH){
lcd.setCursor(1,1);
lcd.print("Chuyen dong ket thuc ");
delay(100);
state=LOW;
}
else{
lcd.setCursor(3,0);
if(now.hour()<=9)
{
lcd.print("0");
lcd.print(now.hour());// nếu sô giờ nhỏ hơn 10 thì thêm số 0 đằng trc để thành 0x
}
else {
lcd.print(now.hour());
}
lcd.print(':');
if(now.minute()<=9)
{
lcd.print("0");
lcd.print(now.minute());
}
else {
lcd.print(now.minute());
}
lcd.print(':');
if(now.second()<=9)
{
lcd.print("0");
lcd.print(now.second());
}
else {
lcd.print(now.second());
}
lcd.println();
lcd.setCursor(2,1);
lcd.print(daysOfTheWeek[now.dayOfTheWeek()]);
lcd.print(",");
if(now.day()<=9)
{
lcd.print("0");
lcd.print(now.day());
}
else {
lcd.print(now.day());
}
lcd.print('/');
if(now.month()<=9)
{
lcd.print("0");
lcd.print(now.month());
}
else {
lcd.print(now.month());
}
lcd.print('/');
if(now.year()<=9)
{
lcd.print("0");
lcd.print(now.year());
}
else {
lcd.print(now.year());
}
lcd.println();
delay(1000);
}
}
}