Compare commits

...

6 Commits

Author SHA1 Message Date
quynhnm
342e88148d new version 2024-08-15 11:10:26 +07:00
quynhnm
c2e38e7de3 mv file 2024-08-15 10:58:35 +07:00
thaonguyen
a9c357a482 them settime cho ds1307 2022-09-15 10:57:42 +07:00
562df9e4f0 . 2021-06-09 10:31:00 +07:00
05616e8868 add light sensor p2 2021-06-09 10:24:59 +07:00
65daad87ac Clear 2021-01-14 14:58:41 +07:00
4 changed files with 500 additions and 605 deletions

BIN
Lock.rar

Binary file not shown.

View File

@ -35,37 +35,13 @@
*/ */
#include <EEPROM.h> // We are going to read and write PICC's UIDs from/to EEPROM #include <EEPROM.h> // We are going to read and write PICC's UIDs from/to EEPROM
#include <SPI.h> // RC522 Module uses SPI protocol
#include <MFRC522.h> // Library for Mifare RC522 Devices
#include <avr/wdt.h> #include <avr/wdt.h>
/*
Instead of a Relay you may want to use a servo. Servos can lock and unlock door locks too
Relay will be used by default
*/
// #include <Servo.h>
//#define COMMON_ANODE
// Ver 1
//#ifdef COMMON_ANODE
//#define LED_ON LOW
//#define LED_OFF HIGH
//#else
//#define LED_ON HIGH
//#define LED_OFF LOW
//#endif
//
//#define Light 7
#define ledView 13 #define ledView 13
//
//#define redLed 3 // Set Led Pins
//#define greenLed 6
//#define blueLed 5
//
//#define relay A2 //8 // Set Relay Pin
//#define wipeB 2 // Button pin for WipeMode
//#define button 7 // button exit
// --------------------------------------------
//Ver 3 //Ver 3
// LED 12V - A1 // LED 12V - A1
//Relay 1 - D5 //Relay 1 - D5
@ -91,297 +67,66 @@
#define relay_2 6 //6 // Set Relay 1 Pin #define relay_2 6 //6 // Set Relay 1 Pin
#define button_2 8 // button exit #define button_2 8 // button exit
#define wipeB A0 // Button pin for WipeMode
#define Light A1 // Led tro sang camera #define Light A1 // Led tro sang camera
//------------------------
#define ss A0
int stt_ss;
int stt_old_ss;
String input_ss;
int th = 1023; // ngưỡng
int time_get = 250;
//------------------------
int stt;
int stt_old;
String input;
int stt_2;
int stt_old_2;
String input_2;
bool Light_stt = false; bool Light_stt = false;
bool relay_stt = false; bool relay_stt = false;
bool relay_stt_2 = false; bool relay_stt_2 = false;
bool sttRun = false; bool sttRun = false;
bool programMode = false; // initialize programming mode to false
uint8_t successRead; // Variable integer to keep if we have Successful Read from Reader
byte storedCard[4]; // Stores an ID read from EEPROM
byte readCard[4]; // Stores scanned ID read from RFID Module
byte masterCard[4]; // Stores master card's ID read from EEPROM
// Create MFRC522 instance.
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);
bool Debug = false; bool Debug = false;
///////////////////////////////////////// Setup /////////////////////////////////// ///////////////////////////////////////// Setup ///////////////////////////////////
void setup() void setup()
{ {
//Arduino Pin Configuration
pinMode(13, OUTPUT); pinMode(13, OUTPUT);
pinMode(Light, OUTPUT); pinMode(Light, OUTPUT);
digitalWrite(13, LOW); digitalWrite(13, LOW);
//Arduino Pin Configuration
pinMode(ledView, OUTPUT); pinMode(ledView, OUTPUT);
pinMode(redLed, OUTPUT); pinMode(ss, INPUT);
pinMode(greenLed, OUTPUT);
pinMode(blueLed, OUTPUT);
pinMode(wipeB, INPUT_PULLUP); // Enable pin's pull up resistor
pinMode(relay, OUTPUT); pinMode(relay, OUTPUT);
pinMode(relay_2, OUTPUT); pinMode(relay_2, OUTPUT);
pinMode(button,INPUT); pinMode(button, INPUT);
pinMode(button_2,INPUT); pinMode(button_2, INPUT);
//Be careful how relay circuit behave on while resetting or power-cycling your Arduino
digitalWrite(relay, HIGH); // Make sure door is locked digitalWrite(relay, HIGH); // Make sure door is locked
digitalWrite(relay_2, HIGH); // Make sure door is locked digitalWrite(relay_2, HIGH); // Make sure door is locked
// delay(2000);
// digitalWrite(relay, LOW);
// delay(2000);
// digitalWrite(relay_2, HIGH); // Make sure door is locked
// delay(2000);
// digitalWrite(redLed, LED_OFF); // Make sure led is off
// digitalWrite(greenLed, LED_OFF); // Make sure led is off
// digitalWrite(blueLed, LED_OFF); // Make sure led is off
digitalWrite(Light, LOW); digitalWrite(Light, LOW);
//Protocol Configuration //Protocol Configuration
Serial.begin(9600); // Initialize serial communications with PC Serial.begin(9600); // Initialize serial communications with PC
//
// SPI.begin(); // MFRC522 Hardware uses SPI protocol
// mfrc522.PCD_Init(); // Initialize MFRC522 Hardware
// if (Debug == true)
// {
// //If you set Antenna Gain to Max it will increase reading distance
// mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
// Serial.println(F("Access Control Example v0.1")); // For debugging purposes
// }
//
// ShowReaderDetails(); // Show details of PCD - MFRC522 Card Reader details
//
// //Wipe Code - If the Button (wipeB) Pressed while setup run (powered on) it wipes EEPROM
// if (digitalRead(wipeB) == LOW)
// { // when button pressed pin should get low, button connected to ground
// digitalWrite(redLed, LED_ON); // Red Led stays on to inform user we are going to wipe
// if (Debug == 1)
// {
// Serial.println(F("Wipe Button Pressed"));
// Serial.println(F("You have 10 seconds to Cancel"));
// Serial.println(F("This will be remove all records and cannot be undone"));
// }
// bool buttonState = monitorWipeButton(10000); // Give user enough time to cancel operation
// if (buttonState == true && digitalRead(wipeB) == LOW)
// { // If button still be pressed, wipe EEPROM
// // Serial.println(F("Starting Wiping EEPROM"));
// for (uint16_t x = 0; x < EEPROM.length(); x = x + 1)
// { //Loop end of EEPROM address
// if (EEPROM.read(x) == 0)
// { //If EEPROM address 0
// // do nothing, already clear, go to the next address in order to save time and reduce writes to EEPROM
// }
// else
// {
// EEPROM.write(x, 0); // if not write 0 to clear, it takes 3.3mS
// }
// }
// // Serial.println(F("EEPROM Successfully Wiped"));
// digitalWrite(redLed, LED_OFF); // visualize a successful wipe
// delay(200);
// digitalWrite(redLed, LED_ON);
// delay(200);
// digitalWrite(redLed, LED_OFF);
// delay(200);
// digitalWrite(redLed, LED_ON);
// delay(200);
// digitalWrite(redLed, LED_OFF);
// }
// else
// {
// // Serial.println(F("Wiping Cancelled")); // Show some feedback that the wipe button did not pressed for 15 seconds
// digitalWrite(redLed, LED_OFF);
// }
// }
// // Check if master card defined, if not let user choose a master card
// // This also useful to just redefine the Master Card
// // You can keep other EEPROM records just write other than 143 to EEPROM address 1
// // EEPROM address 1 should hold magical number which is '143'
// if (EEPROM.read(1) != 143)
// {
// if (Debug == 1)
// {
// Serial.println(F("No Master Card Defined"));
// Serial.println(F("Scan A PICC to Define as Master Card"));
// }
//
// do
// {
// successRead = getID(); // sets successRead to 1 when we get read from reader otherwise 0
// digitalWrite(blueLed, LED_ON); // Visualize Master Card need to be defined
// delay(200);
// digitalWrite(blueLed, LED_OFF);
// delay(200);
// } while (!successRead); // Program will not go further while you not get a successful read
// for (uint8_t j = 0; j < 4; j++)
// { // Loop 4 times
// EEPROM.write(2 + j, readCard[j]); // Write scanned PICC's UID to EEPROM, start from address 3
// }
// EEPROM.write(1, 143); // Write to EEPROM we defined Master Card.
// if (Debug == 1)
// {
// Serial.println(F("Master Card Defined"));
// }
// }
// if (Debug == 1)
// {
// Serial.println(F("-------------------"));
// Serial.println(F("Master Card's UID"));
// }
//
// for (uint8_t i = 0; i < 4; i++)
// { // Read Master Card's UID from EEPROM
// masterCard[i] = EEPROM.read(2 + i); // Write it to masterCard
// if (Debug == 1)
// {
// Serial.print(masterCard[i], HEX);
// }
// }
// if (Debug == 1)
// {
// Serial.println("");
// Serial.println(F("-------------------"));
// Serial.println(F("Everything is ready"));
// Serial.println(F("Waiting PICCs to be scanned"));
// }
//
// cycleLeds(); // Everything ready lets give user some feedback by cycling leds
// // }
// // wdt_enable(WDTO_500MS);
} }
//void SerialRead();
//void ReadButton();
///////////////////////////////////////// Main Loop /////////////////////////////////// ///////////////////////////////////////// Main Loop ///////////////////////////////////
void loop() void loop()
{ {
ReadLightSS();
ReadButton(); ReadButton();
SerialRead(); SerialRead();
CheckButton(); CheckButton();
} }
// do
// {
// ReadButton();
// SerialRead();
//
// successRead = getID(); // sets successRead to 1 when we get read from reader otherwise 0
// // When device is in use if wipe button pressed for 10 seconds initialize Master Card wiping
// if (digitalRead(wipeB) == LOW)
// { // Check if button is pressed
// // Visualize normal operation is iterrupted by pressing wipe button Red is like more Warning to user
// digitalWrite(redLed, LED_ON); // Make sure led is off
// digitalWrite(greenLed, LED_OFF); // Make sure led is off
// digitalWrite(blueLed, LED_OFF); // Make sure led is off
// // Give some feedback
// if (Debug == 1)
// {
// Serial.println(F("Wipe Button Pressed"));
// Serial.println(F("Master Card will be Erased! in 10 seconds"));
// }
//
// bool buttonState = monitorWipeButton(10000); // Give user enough time to cancel operation
// if (buttonState == true && digitalRead(wipeB) == LOW)
// { // If button still be pressed, wipe EEPROM
// EEPROM.write(1, 0); // Reset Magic Number.
// if (Debug == 1)
// {
// Serial.println(F("Master Card Erased from device"));
// Serial.println(F("Please reset to re-program Master Card"));
// }
// while (1)
// ;
// }
// // Serial.println(F("Master Card Erase Cancelled"));
// }
// if (programMode)
// {
// cycleLeds(); // Program Mode cycles through Red Green Blue waiting to read a new card
// }
// else
// {
// normalModeOn(); // Normal mode, blue Power LED is on, all others are off
// }
// CheckButton();
// } while (!successRead); //the program will not go further while you are not getting a successful read
//
// if (programMode)
// {
// if (isMaster(readCard))
// { //When in program mode check First If master card scanned again to exit program mode
// // Serial.println(F("Master Card Scanned"));
// // Serial.println(F("Exiting Program Mode"));
// // Serial.println(F("-----------------------------"));
// programMode = false;
// return;
// }
// else
// {
// if (findID(readCard))
// { // If scanned card is known delete it
// // Serial.println(F("I know this PICC, removing..."));
// deleteID(readCard);
// // Serial.println("-----------------------------");
// // Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
// }
// else
// { // If scanned card is not known add it
// // Serial.println(F("I do not know this PICC, adding..."));
// writeID(readCard);
// // Serial.println(F("-----------------------------"));
// // Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
// }
// }
// }
// else
// {
// if (isMaster(readCard))
// { // If scanned card's ID matches Master Card's ID - enter program mode
// programMode = true;
// // Serial.println(F("Hello Master - Entered Program Mode"));
// uint8_t count = EEPROM.read(0); // Read the first Byte of EEPROM that
// // Serial.print(F("I have ")); // stores the number of ID's in EEPROM
// // Serial.print(count);
// // Serial.print(F(" record(s) on EEPROM"));
// // Serial.println("");
// // Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
// // Serial.println(F("Scan Master Card again to Exit Program Mode"));
// // Serial.println(F("-----------------------------"));
// }
// else
// {
// if (findID(readCard))
// { // If not, see if the card is in the EEPROM
// // Serial.println(F("Welcome, You shall pass"));
// relay_stt = true;
// granted(4000); // Open the door lock for 300 ms
// ClearSerialdata();
// }
// else
// { // If not, show that the ID was not valid
// // Serial.println(F("You shall not pass"));
// denied();
// }
// }
// }
//
//}
//----------------------------------------
// wdt_reset();
//}
///////////////////////////////////////// Access Granted /////////////////////////////////// ///////////////////////////////////////// Access Granted ///////////////////////////////////
// Turn on Light camera // Turn on Light camera
@ -396,9 +141,7 @@ void TurnOff_Light() {
void granted(uint16_t setDelay) void granted(uint16_t setDelay)
{ {
digitalWrite(blueLed, LED_OFF); // Turn off blue LED
digitalWrite(redLed, LED_OFF); // Turn off red LED
digitalWrite(greenLed, LED_ON); // Turn on green LED
digitalWrite(relay, LOW); // Unlock door! digitalWrite(relay, LOW); // Unlock door!
digitalWrite(ledView, LOW); digitalWrite(ledView, LOW);
delay(setDelay); // Hold door lock open for given seconds delay(setDelay); // Hold door lock open for given seconds
@ -409,323 +152,22 @@ void granted(uint16_t setDelay)
void granted_2(uint16_t setDelay) void granted_2(uint16_t setDelay)
{ {
digitalWrite(blueLed, LED_OFF); // Turn off blue LED
digitalWrite(redLed, LED_OFF); // Turn off red LED
digitalWrite(greenLed, LED_ON); // Turn on green LED
digitalWrite(relay_2, LOW); // Unlock door! digitalWrite(relay_2, LOW); // Unlock door!
digitalWrite(ledView, LOW); digitalWrite(ledView, LOW);
// digitalWrite(Light, HIGH);
delay(setDelay); // Hold door lock open for given seconds delay(setDelay); // Hold door lock open for given seconds
digitalWrite(relay_2, HIGH); // Relock door digitalWrite(relay_2, HIGH); // Relock door
digitalWrite(ledView, HIGH); digitalWrite(ledView, HIGH);
// digitalWrite(Light, LOW);
delay(200); // Hold green LED on for a second delay(200); // Hold green LED on for a second
} }
///////////////////////////////////////// Access Denied ///////////////////////////////////
void denied()
{
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
digitalWrite(redLed, LED_ON); // Turn on red LED
delay(1000);
}
///////////////////////////////////////// Get PICC's UID ///////////////////////////////////
uint8_t getID()
{
// Getting ready for Reading PICCs
if (!mfrc522.PICC_IsNewCardPresent())
{ //If a new PICC placed to RFID reader continue
return 0;
}
if (!mfrc522.PICC_ReadCardSerial())
{ //Since a PICC placed get Serial and continue
return 0;
}
// There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC
// I think we should assume every PICC as they have 4 byte UID
// Until we support 7 byte PICCs
// Serial.println(F("Scanned PICC's UID:"));
for (uint8_t i = 0; i < 4; i++)
{ //
readCard[i] = mfrc522.uid.uidByte[i];
// Serial.print(readCard[i], HEX);
}
// Serial.println("");
mfrc522.PICC_HaltA(); // Stop reading
return 1;
}
int k;
void ShowReaderDetails()
{
// Get the MFRC522 software version
byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
// Serial.print(F("MFRC522 Software Version: 0x"));
// Serial.print(v, HEX);
if (v == 0x91)
// Serial.print(F(" = v1.0"));
k = 0;
else if (v == 0x92)
// Serial.print(F(" = v2.0"));
k = 1;
else
// Serial.print(F(" (unknown),probably a chinese clone?"));
// Serial.println("");
// When 0x00 or 0xFF is returned, communication probably failed
if ((v == 0x00) || (v == 0xFF))
{
// Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
// Serial.println(F("SYSTEM HALTED: Check connections."));
// Visualize system is halted
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
digitalWrite(redLed, LED_ON); // Turn on red LED
while (true)
; // do not go further
}
}
///////////////////////////////////////// Cycle Leds (Program Mode) ///////////////////////////////////
void cycleLeds()
{
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
digitalWrite(greenLed, LED_ON); // Make sure green LED is on
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
delay(200);
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
digitalWrite(blueLed, LED_ON); // Make sure blue LED is on
delay(200);
digitalWrite(redLed, LED_ON); // Make sure red LED is on
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
delay(200);
}
//////////////////////////////////////// Normal Mode Led ///////////////////////////////////
void normalModeOn()
{
digitalWrite(blueLed, LED_ON); // Blue LED ON and ready to read card
digitalWrite(redLed, LED_OFF); // Make sure Red LED is off
digitalWrite(greenLed, LED_OFF); // Make sure Green LED is off
digitalWrite(relay, HIGH); // Make sure Door is Locked
digitalWrite(ledView, HIGH);
}
//////////////////////////////////////// Read an ID from EEPROM //////////////////////////////
void readID(uint8_t number)
{
uint8_t start = (number * 4) + 2; // Figure out starting position
for (uint8_t i = 0; i < 4; i++)
{ // Loop 4 times to get the 4 Bytes
storedCard[i] = EEPROM.read(start + i); // Assign values read from EEPROM to array
}
}
///////////////////////////////////////// Add ID to EEPROM ///////////////////////////////////
void writeID(byte a[])
{
if (!findID(a))
{ // Before we write to the EEPROM, check to see if we have seen this card before!
uint8_t num = EEPROM.read(0); // Get the numer of used spaces, position 0 stores the number of ID cards
uint8_t start = (num * 4) + 6; // Figure out where the next slot starts
num++; // Increment the counter by one
EEPROM.write(0, num); // Write the new count to the counter
for (uint8_t j = 0; j < 4; j++)
{ // Loop 4 times
EEPROM.write(start + j, a[j]); // Write the array values to EEPROM in the right position
}
successWrite();
// Serial.println(F("Succesfully added ID record to EEPROM"));
}
else
{
failedWrite();
// Serial.println(F("Failed! There is something wrong with ID or bad EEPROM"));
}
}
///////////////////////////////////////// Remove ID from EEPROM ///////////////////////////////////
void deleteID(byte a[])
{
if (!findID(a))
{ // Before we delete from the EEPROM, check to see if we have this card!
failedWrite(); // If not
// Serial.println(F("Failed! There is something wrong with ID or bad EEPROM"));
}
else
{
uint8_t num = EEPROM.read(0); // Get the numer of used spaces, position 0 stores the number of ID cards
uint8_t slot; // Figure out the slot number of the card
uint8_t start; // = ( num * 4 ) + 6; // Figure out where the next slot starts
uint8_t looping; // The number of times the loop repeats
uint8_t j;
uint8_t count = EEPROM.read(0); // Read the first Byte of EEPROM that stores number of cards
slot = findIDSLOT(a); // Figure out the slot number of the card to delete
start = (slot * 4) + 2;
looping = ((num - slot) * 4);
num--; // Decrement the counter by one
EEPROM.write(0, num); // Write the new count to the counter
for (j = 0; j < looping; j++)
{ // Loop the card shift times
EEPROM.write(start + j, EEPROM.read(start + 4 + j)); // Shift the array values to 4 places earlier in the EEPROM
}
for (uint8_t k = 0; k < 4; k++)
{ // Shifting loop
EEPROM.write(start + j + k, 0);
}
successDelete();
// Serial.println(F("Succesfully removed ID record from EEPROM"));
}
}
///////////////////////////////////////// Check Bytes ///////////////////////////////////
bool checkTwo(byte a[], byte b[])
{
for (uint8_t k = 0; k < 4; k++)
{ // Loop 4 times
if (a[k] != b[k])
{ // IF a != b then false, because: one fails, all fail
return false;
}
}
return true;
}
///////////////////////////////////////// Find Slot ///////////////////////////////////
uint8_t findIDSLOT(byte find[])
{
uint8_t count = EEPROM.read(0); // Read the first Byte of EEPROM that
for (uint8_t i = 1; i <= count; i++)
{ // Loop once for each EEPROM entry
readID(i); // Read an ID from EEPROM, it is stored in storedCard[4]
if (checkTwo(find, storedCard))
{ // Check to see if the storedCard read from EEPROM
// is the same as the find[] ID card passed
return i; // The slot number of the card
}
}
}
///////////////////////////////////////// Find ID From EEPROM ///////////////////////////////////
bool findID(byte find[])
{
uint8_t count = EEPROM.read(0); // Read the first Byte of EEPROM that
for (uint8_t i = 1; i < count; i++)
{ // Loop once for each EEPROM entry
readID(i); // Read an ID from EEPROM, it is stored in storedCard[4]
if (checkTwo(find, storedCard))
{ // Check to see if the storedCard read from EEPROM
return true;
}
else
{ // If not, return false
}
}
return false;
}
///////////////////////////////////////// Write Success to EEPROM ///////////////////////////////////
// Flashes the green LED 3 times to indicate a successful write to EEPROM
void successWrite()
{
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
digitalWrite(greenLed, LED_OFF); // Make sure green LED is on
delay(200);
digitalWrite(greenLed, LED_ON); // Make sure green LED is on
delay(200);
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
delay(200);
digitalWrite(greenLed, LED_ON); // Make sure green LED is on
delay(200);
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
delay(200);
digitalWrite(greenLed, LED_ON); // Make sure green LED is on
delay(200);
}
///////////////////////////////////////// Write Failed to EEPROM ///////////////////////////////////
// Flashes the red LED 3 times to indicate a failed write to EEPROM
void failedWrite()
{
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
delay(200);
digitalWrite(redLed, LED_ON); // Make sure red LED is on
delay(200);
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
delay(200);
digitalWrite(redLed, LED_ON); // Make sure red LED is on
delay(200);
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
delay(200);
digitalWrite(redLed, LED_ON); // Make sure red LED is on
delay(200);
}
///////////////////////////////////////// Success Remove UID From EEPROM ///////////////////////////////////
// Flashes the blue LED 3 times to indicate a success delete to EEPROM
void successDelete()
{
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
delay(200);
digitalWrite(blueLed, LED_ON); // Make sure blue LED is on
delay(200);
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
delay(200);
digitalWrite(blueLed, LED_ON); // Make sure blue LED is on
delay(200);
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
delay(200);
digitalWrite(blueLed, LED_ON); // Make sure blue LED is on
delay(200);
}
////////////////////// Check readCard IF is masterCard ///////////////////////////////////
// Check to see if the ID passed is the master programing card
bool isMaster(byte test[])
{
return checkTwo(test, masterCard);
}
bool monitorWipeButton(uint32_t interval)
{
uint32_t now = (uint32_t)millis();
while ((uint32_t)millis() - now < interval)
{
// check on every half a second
if (((uint32_t)millis() % 500) == 0)
{
if (digitalRead(wipeB) != LOW)
return false;
}
}
return true;
}
// ADD Code // ADD Code
int stt;
int stt_old;
String input;
int stt_2;
int stt_old_2;
String input_2;
void ReadButton() void ReadButton()
{ {
stt = digitalRead(button); stt = digitalRead(button);
stt_2 = digitalRead(button_2); stt_2 = digitalRead(button_2);
// Serial.print(stt);
// Serial.print("\t");
// Serial.println(stt_2);
if (stt == 0 && stt_old == 1) if (stt == 0 && stt_old == 1)
{ {
relay_stt = true; relay_stt = true;
@ -748,6 +190,45 @@ void ReadButton()
stt_old = stt; stt_old = stt;
stt_old_2 = stt_2; stt_old_2 = stt_2;
} }
//Read Light Sensor
bool stt_msg = false;
void ReadLightSS()
{
// stt_ss = digitalRead(ss);
int val = analogRead(A0);
if (val > th) {
delay (time_get);
int val = analogRead(A0);
if (val > th) {
stt_ss = 1;
} else {
stt_ss = 0;
}
} else {
stt_ss = 0;
}
//
if (stt_ss == 1 && stt_old_ss == 0)
{
stt_msg = true; // bật cờ gửi tín hiệu cho engine bật ads
Light_stt = !Light_stt;
if (Light_stt == 1) {
TurnOn_Light();
// Serial.println("Light sensor press ON");
}
else {
TurnOff_Light();
// Serial.println("Light sensor press OFF");
}
}
if (stt_msg == true){
Serial.println("open_bf");
ClearSerialdata();
}
stt_old_ss = stt_ss;
}
@ -787,7 +268,7 @@ void SerialRead()
} }
Serial.println("open_1"); Serial.println("open_1");
ClearSerialdata(); ClearSerialdata();
}else if (input == "2") } else if (input == "2")
{ {
if (relay_stt_2 == false) if (relay_stt_2 == false)
@ -797,8 +278,11 @@ void SerialRead()
} }
Serial.println("open_2"); Serial.println("open_2");
ClearSerialdata(); ClearSerialdata();
} } else if (input == "recv_bf")
else {
stt_msg = false;
ClearSerialdata();
} else
{ {
digitalWrite(13, LOW); digitalWrite(13, LOW);
} }

90
Lock/lock_main_202407.ino Normal file
View File

@ -0,0 +1,90 @@
const int ledPin1 = 5; // Chân kết nối LED 1
const int ledPin2 = 6; // Chân kết nối LED 2
const int buttonPin1 = 7; // Chân kết nối nút nhấn 1
const int buttonPin2 = 8; // Chân kết nối nút nhấn 2
bool ledState1 = false; // Trạng thái của LED 1
bool ledState2 = false; // Trạng thái của LED 2
#define Light A1 // Led tro sang camera
unsigned long previousMillis1 = 0; // Thời điểm lưu trữ cho LED 1
unsigned long previousMillis2 = 0; // Thời điểm lưu trữ cho LED 2
int timedelay= 5000;
void setup() {
pinMode(ledPin1, OUTPUT); // Thiết lập chân là OUTPUT cho LED 1
pinMode(ledPin2, OUTPUT); // Thiết lập chân là OUTPUT cho LED 2
pinMode(buttonPin1, INPUT_PULLUP); // Thiết lập chân là INPUT_PULLUP cho nút nhấn 1
pinMode(buttonPin2, INPUT_PULLUP); // Thiết lập chân là INPUT_PULLUP cho nút nhấn 2
digitalWrite(ledPin1, HIGH); // Make sure door is locked
digitalWrite(ledPin2, HIGH); // Make sure door is locked
digitalWrite(Light, LOW);
Serial.begin(9600); // Bắt đầu kết nối Serial
}
void loop() {
checkserial();
readbutton();
checkrelay();
}
void readbutton(){
// Kiểm tra nếu nút nhấn 1 được nhấn
if (digitalRead(buttonPin1) == LOW) {
// Bật LED 1 và ghi lại thời điểm hiện tại
digitalWrite(ledPin1, LOW);
ledState1 = true;
previousMillis1 = millis();
}
// Kiểm tra nếu nút nhấn 2 được nhấn
if (digitalRead(buttonPin2) == LOW) {
// Bật LED 2 và ghi lại thời điểm hiện tại
digitalWrite(ledPin2, LOW);
ledState2 = true;
previousMillis2 = millis();
}
}
void checkserial(){
if (Serial.available() > 0) {
String input = Serial.readStringUntil('\n'); // Đọc từ Serial cho đến khi gặp ký tự xuống dòng
input.trim(); // Loại bỏ các khoảng trắng và ký tự xuống dòng từ đầu và cuối chuỗi
if (input == "1") {
// Bật LED 1 và ghi lại thời điểm hiện tại
digitalWrite(ledPin1, LOW);
Serial.println("open_1");
ledState1 = true;
previousMillis1 = millis();
} else if (input == "2") {
// Bật LED 2 và ghi lại thời điểm hiện tại
digitalWrite(ledPin2, LOW);
Serial.println("open_2");
ledState2 = true;
previousMillis2 = millis();
}else if (input == "3"){
digitalWrite(Light, HIGH);
Serial.println("open_3");
}else if (input == "4"){
digitalWrite(Light, LOW);
Serial.println("open_4");
}else if (input.indexOf("tdoor")!= -1){
int t = input.substring(5,7).toInt();
Serial.println(t);
if (t !=0 && t <=30){
timedelay = t*1000;
}
}
}
}
void checkrelay(){
// Kiểm tra nếu LED 1 đã được bật và thời gian đã trôi qua 1000 ms (1 giây)
if (ledState1 && (millis() - previousMillis1 >= timedelay)) {
digitalWrite(ledPin1, HIGH); // Tắt LED 1
ledState1 = false; // Đặt trạng thái LED 1 về false
}
// Kiểm tra nếu LED 2 đã được bật và thời gian đã trôi qua 1000 ms (1 giây)
if (ledState2 && (millis() - previousMillis2 >= timedelay)) {
digitalWrite(ledPin2, HIGH); // Tắt LED 2
ledState2 = false; // Đặt trạng thái LED 2 về false
}
}

View File

@ -0,0 +1,321 @@
//===============> Version Timer 22/03/2022 Suported by Thaonv <=====================//
#include <SPI.h> // RC522 Module uses SPI protocol
#include "TimerOne.h"
#include <Wire.h>
#define ledView 13
//Ver 3
// LED 12V - A1
//Relay 1 - D5
//Button 1 - D8
// Relay 2 - D6
// Button 2 - D7
long Time_openRelay = 4000 ; // ms - Thoi gian giu mo khoa
#define relay 5 //6 // Set Relay 1 Pin
#define button 7 // button exit
#define relay_2 6 //6 // Set Relay 1 Pin
#define button_2 8 // button exit
#define Light A1 // Led tro sang camera
//------------------------
int stt;
int stt_old;
String input;
/* Địa chỉ của DS1307 */
const byte DS1307 = 0x68;
/* Số byte dữ liệu sẽ đọc từ DS1307 */
const byte NumberOfFields = 7;
/* khai báo các biến thời gian */
int second, minute, hour, day, wday, month, year;
//------------------------
int stt_2;
int stt_old_2;
String input_2;
String timestart;
bool Light_stt = false;
bool relay_stt = false;
bool relay_stt_2 = false;
bool sttRun = false;
bool Debug = false;
//---------------------------------------------------------
unsigned long countFlagRelay_1 = 0;
unsigned long countFlagRelay_2 = 0;
bool kickFlag_1 = false;
bool kickFlag_2 = false;
int day_st,month_st,year_st,second_st,minute_st,hour_st,thu_st;
///////////////////////////////////////// Setup ///////////////////////////////////
void setup()
{
Wire.begin();//i2c
//Arduino Pin Configuration
pinMode(13, OUTPUT);
pinMode(Light, OUTPUT);
digitalWrite(13, LOW);
pinMode(ledView, OUTPUT);
pinMode(relay, OUTPUT);
pinMode(relay_2, OUTPUT);
pinMode(button, INPUT);
pinMode(button_2, INPUT);
digitalWrite(relay, HIGH); // Make sure door is locked
digitalWrite(relay_2, HIGH); // Make sure door is locked
digitalWrite(Light, LOW);
// Init timer
Timer1.initialize(1000); // initialize timer1, and set a 1/2 second period
Timer1.attachInterrupt(funcHandler); // Every x_us
Serial.begin(9600); // Initialize serial communications with PC
}
///////////////////////////////////////// Main Loop ///////////////////////////////////
void loop()
{
ReadButton();
SerialRead();
CheckButton();
}
//----------- Full Function ----------------//
void funcHandler() {
// Relay 1
if ( kickFlag_1 == true ) {
countFlagRelay_1 ++;
if ( countFlagRelay_1 >= Time_openRelay ) {
countFlagRelay_1 = 0;
kickFlag_1 = false;
digitalWrite(relay, HIGH); // Unlock relay 1
//Serial.println("Lock 1");
}
}
// Relay 2
if ( kickFlag_2 == true ) {
countFlagRelay_2 ++;
if ( countFlagRelay_2 >= Time_openRelay ) {
countFlagRelay_2 = 0;
kickFlag_2 = false;
digitalWrite(relay_2, HIGH); // Unlock relay 1
//Serial.println("Lock 2");
}
}
}
// ADD Code
void ReadButton()
{
stt = digitalRead(button);
stt_2 = digitalRead(button_2);
if (stt == 0 && stt_old == 1)
{
relay_stt = true;
//Serial.println("Button 1 press");
}
else
{
relay_stt = false;
}
if (stt_2 == 0 && stt_old_2 == 1)
{
//Serial.println("Button 2 press");
relay_stt_2 = true;
}
else
{
relay_stt_2 = false;
}
stt_old = stt;
stt_old_2 = stt_2;
}
void SerialRead()
{
while (Serial.available() > 0)
{
input = Serial.readStringUntil('\r');
//Serial.println(input);
input.trim();
if(input.indexOf("tdoor")!= -1){ // msg = tdoor_6
int t = input.substring(6).toInt();
if (t !=0 && t <=30){
Time_openRelay = t*1000;
}else{
// Give time old get
}
}
else if (input.indexOf("time_set")!= -1){
timestart = input.substring(8);
hour_st=timestart.substring(0,2).toInt();
minute_st=timestart.substring(3,5).toInt();
second_st=timestart.substring(6,8).toInt();
day_st=timestart.substring(9,11).toInt();
String month_st=timestart.substring(12,14);
if(month_st.indexOf("0")!= -1){
int vitri0 = month_st.indexOf("0"); //5
String Str7 = month_st.substring(vitri0+1,vitri0+2);
month_st=Str7;
}else{
}
int month_st1=month_st.toInt();
year_st=timestart.substring(17,19).toInt();
thu_st=timestart.substring(20,22).toInt();
setTime(hour_st, minute_st, second_st, thu_st, day_st, month_st1, year_st); // 12:30:45 CN 08-02-2015
}
else if (input == "3") {
if (Light_stt == false) {
TurnOn_Light();
}
Serial.println("open_3");
ClearSerialdata();
} else if (input == "4") {
if (Light_stt == true) {
TurnOff_Light();
}
Serial.println("open_4");
ClearSerialdata();
}
else if (input == "1")
{
if (relay_stt == false)
{
relay_stt = true;
}
Serial.println("open_1");
ClearSerialdata();
} else if (input == "2")
{
if (relay_stt_2 == false)
{
relay_stt_2 = true;
}
Serial.println("open_2");
ClearSerialdata();
}else if (input == "5") {
readDS1307();
digitalClockDisplay();
ClearSerialdata();
} else
{
digitalWrite(13, LOW);
}
}
ClearSerialdata();
}
void CheckButton()
{
if (relay_stt == true)
{
digitalWrite(relay, LOW); // Unlock relay 1'
noInterrupts(); //Hủy các ngắt trước đó.
kickFlag_1 = true;
interrupts(); //Cho phép ngắt
relay_stt = false;
ClearSerialdata();
}
//-------------------------
if (relay_stt_2 == true)
{
digitalWrite(relay_2, LOW); // Unlock relay 1
kickFlag_2 = true;
relay_stt_2 = false;
ClearSerialdata();
}
}
// Turn on Light camera
void TurnOn_Light() {
digitalWrite(Light, HIGH);
Light_stt = true;
}
void TurnOff_Light() {
digitalWrite(Light, LOW);
Light_stt = false;
}
void ClearSerialdata()
{
while (Serial.available() > 0)
{
char c = Serial.read();
}
}
//get time từ ds1307
void readDS1307()
{
Wire.beginTransmission(DS1307);
Wire.write((byte)0x00);
Wire.endTransmission();
Wire.requestFrom(DS1307, NumberOfFields);
second = bcd2dec(Wire.read() & 0x7f);
minute = bcd2dec(Wire.read() );
hour = bcd2dec(Wire.read() & 0x3f); // chế độ 24h.
wday = bcd2dec(Wire.read() );
day = bcd2dec(Wire.read() );
month = bcd2dec(Wire.read() );
year = bcd2dec(Wire.read() );
year += 2000;
}
/* Chuyển từ format BCD (Binary-Coded Decimal) sang Decimal */
int bcd2dec(byte num)
{
return ((num / 16 * 10) + (num % 16));
}
/* Chuyển từ Decimal sang BCD */
int dec2bcd(byte num)
{
return ((num / 10 * 16) + (num % 10));
}
void digitalClockDisplay() {
// digital clock display of the time
Serial.print(hour);
printDigits(minute);
printDigits(second);
Serial.print(" ");
Serial.print(day);
Serial.print(" ");
Serial.print(month);
Serial.print(" ");
Serial.print(year);
Serial.println();
}
void printDigits(int digits) {
// các thành phần thời gian được ngăn chách bằng dấu :
Serial.print(":");
if (digits < 10)
Serial.print('0');
Serial.print(digits);
}
void setTime(byte hr, byte min, byte sec, byte wd, byte d, byte mth, byte yr) // byte wd,
{
Wire.beginTransmission(DS1307);
Wire.write(byte(0x00)); // đặt lại pointer
Wire.write(dec2bcd(sec));
Wire.write(dec2bcd(min));
Wire.write(dec2bcd(hr));
Wire.write(dec2bcd(wd)); // day of week: Sunday = 1, Saturday = 7
Wire.write(dec2bcd(d));
Wire.write(dec2bcd(mth));
Wire.write(dec2bcd(yr));
Wire.endTransmission();
}
//////////////////////////////////////