Arduino Bitirme Projeleri Arduino ile RFID Kapı Kilidi By Konuk Yazar Posted on 4 Haziran 2015 31 min read 30 0 43,406 Paylaş ! Facebook Paylaş ! Twitter Paylaş ! Google+ Paylaş ! Reddit Paylaş ! Pinterest Paylaş ! Linkedin Paylaş ! Tumblr Merhaba arkadaşlar, Mehmet Akif Ersoy Üniversitesi,Çavdır Meslek Yüksek Okulu öğrencilerinden Semih Demirhan arkadaşımızın yapmış olduğu,Arduino ile RFID kapı kilidi çalışmasını,detaylı olarak sizlerle paylaşıyoruz.İlk önce proje videosunu izleyelim ve biraz projemizi tanıyalım. [ÖNEMLİ] Arkadaşlar,başlamadan şunu da söylemek isteriz.Eğer bu projeyi kendiniz uygulamak isterseniz,yazımızı baştan sona kadar okumanızı tavsiye ederiz.Aksi takdirde kopukluk yaşanabilir. Kullanılan Malzemeler Arduino Uno 5110 Lcd Ekran Mfrc522 Rfid Röle Buzzer Kırmızı ve Yeşil Led 5 volt Adaptör Gizli Kapı Otomatiği(12 volt adaptör kullanıldı) Not:Pin bağlantıları kod içerisinde de yorum olarak açıklanmaktadır. LCD5110 LCD ile ilgili detaylı bilgiye buradan ulaşabilirsiniz.LCD5110 ile arduino arasındaki bağlantılar aşağıda gösterilmektedir.//LCD5110 myGLCD(8,9,10,11,12); RST 7 CE 6 DC 5 DİN 4 CLK 3 VCC 3.3V BL 3.3V GND-GND MFRC522 MFRC522 hakkında detaylı bilgiye buradan ulaşabilirsiniz.MFRC522’nin,Arduino ile bağlantıları aşağıda gösterilmektedir. (Arduino Uno): * MOSI: Pin 11 / ICSP-4 * MISO: Pin 12 / ICSP-1 * SCK : Pin 13 / ICSP-3 * SS : Pin 10 * RST : Pin 9 RÖLE DEVRESİ Burada kapı otomatiği de kullanmıştık.Kapı otomatiğini direk arduino çıkışına bağlayamayız.Bildiğiniz gibi,Arduino çıkışından 12 volta göre düşük bir vardır.Bu gibi durumlarda röle devresi kullanılabilir.Bizde çalışmamızda röle devresi kullandık.Röle devresi hakkında detaylı bilgiye buradan ulaşabilirsiniz.Gerekli devre şeması vs. önceki yazımızda detaylı verilmiştir. Ayrıca,arduino’nun 8 nolu çıkışını röleye bağlamalıyız. BUZZER Arduino ile buzzer bağlantısı,arduinomuzun A3 nolu çıkışıdır.Tabi burada buzzer kullanmak isteğe bağlıdır.İhtiyaç görülmediği sürece kullanılmayabilir. KART OKUMA VE SİLME Eklenen karti ayni sekilde okuttuğumuzda da silebilirsiniz. ARDUİNO KODLARI Aşağıdaki kodlarını arduinoda derlemeden önce yapmamız gereken başka bir işlem de,kütüphaneleri eklemek.Kütüphanelerin hepsine buradan ulaşabilirsiniz.Kütüphaneleri indirdikten sonra yapmamız gereken,kütüphanelerin hepsini kopyalayıp,arduino klasörü içerisindeki kütüphanelerin bulunduğu klasöre yapıştırmak. Proje dosyalarına buradan ulaşabilirsiniz. [php] #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 <LCD5110_Basic.h> #include <pitches.h> LCD5110 myGLCD(3,4,5,7,6); //LCD5110 myGLCD(8,9,10,11,12); //RST 7 //CE 6 //DC 5 // DİN 4 //CLK 3 //VCC 3.3V //BL 3.3V //GND-GND extern uint8_t SmallFont[]; int access_melody[] = {NOTE_G4,0,NOTE_A4,0, NOTE_B4,0,NOTE_A4,0,NOTE_B4,0, NOTE_C5,0}; int access_noteDurations[] = {8,8,8,8,8,4,8,8,8,8,8,4}; int fail_melody[] = {NOTE_G2,0,NOTE_F2,0,NOTE_D2,0}; int fail_noteDurations[] = {8,8,8,8,8,4}; #define COMMON_ANODE #ifdef COMMON_ANODE #define LED_ON LOW #define LED_OFF HIGH #else #define LED_ON HIGH #define LED_OFF LOW #endif #define redLed A0 #define greenLed A5 #define relay 8 #define wipeB A4 // Button pin for WipeMode int buzzPin = A3; boolean match = false; // initialize card match to false boolean programMode = false; // initialize programming mode to false int 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 /* We need to define MFRC522’s pins and create instance * Pin layout should be as follows (on Arduino Uno): * MOSI: Pin 11 / ICSP-4 * MISO: Pin 12 / ICSP-1 * SCK : Pin 13 / ICSP-3 * SS : Pin 10 (Configurable) * RST : Pin 9 (Configurable) * look MFRC522 Library for * pin configuration for other Arduinos. */ #define SS_PIN 10 #define RST_PIN 9 MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance. ///////////////////////////////////////// Setup /////////////////////////////////// void setup() { myGLCD.InitLCD(); myGLCD.setFont(SmallFont); //Arduino Pin Configuration pinMode(A2, OUTPUT); pinMode(A5, OUTPUT); pinMode(relay, OUTPUT); digitalWrite(relay, LOW); // Make sure door is locked digitalWrite(redLed, LED_OFF); // Make sure led is off digitalWrite(greenLed, LED_OFF); // Make sure led is off //Protocol Configuration // Serial.begin(9600); // Initialize serial communications with PC SPI.begin(); // MFRC522 Hardware uses SPI protocol mfrc522.PCD_Init(); // Initialize MFRC522 Hardware mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max); //Set Antenna Gain to Max- this will increase reading distance //Wipe Code if Button Pressed while setup run (powered on) it wipes EEPROM pinMode(wipeB, INPUT_PULLUP); // Enable pin’s pull up resistor 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 // Serial.println("Wipe Button Pressed"); //Serial.println("You have 5 seconds to Cancel"); //Serial.println("This will be remove all records and cannot be undone"); delay(5000); // Give user enough time to cancel operation if (digitalRead(wipeB) == LOW) { // If button still be pressed, wipe EEPROM //Serial.println("Starting Wiping EEPROM"); for (int x=0; x<1024; 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, it takes 3.3mS } } //Serial.println("Wiped"); digitalWrite(redLed, LED_OFF); // visualize 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("!!! Wiping Cancelled !!!"); digitalWrite(redLed, LED_OFF); } } //Check if master card defined, if not let user choose a master card //This also useful to just redefine Master Card //You can keep other EEPROM records just write other than 1 to EEPROM address 1 if (EEPROM.read(1) != 143) { // Look EEPROM if Master Card defined, EEPROM address 1 holds if defined // 143 our magical number myGLCD.clrScr(); myGLCD.print("UYARI:", LEFT, 0); myGLCD.print("MASTER KART", CENTER, 16); myGLCD.print("TANIMLANMAMIS", CENTER, 24); delay (2500); myGLCD.clrScr(); myGLCD.print("UYARI:", LEFT, 0); myGLCD.print("LUTFEN KARTI", CENTER, 16); myGLCD.print("YAKLASTIRIN", CENTER, 24); do { successRead = getID(); // sets successRead to 1 when we get read from reader otherwise 0 } while (!successRead); //the program will not go further while you not get a successful read for ( int 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. myGLCD.clrScr(); myGLCD.print("MESAJ:", LEFT, 0); myGLCD.print("YETKILI", CENTER, 10); myGLCD.print("EKLEMESI", CENTER, 16); myGLCD.print("BASARILI", CENTER, 24); delay (2500); myGLCD.clrScr(); } for ( int i = 0; i < 4; i++ ) { // Read Master Card’s UID from EEPROM masterCard[i] = EEPROM.read(2+i); // Write it to masterCard //Serial.print(masterCard[i], HEX); } myGLCD.print("CAVDIR MYO:", LEFT, 0); myGLCD.print("LUTFEN KARTI", CENTER, 16); myGLCD.print("OKUTUN", CENTER, 24); cycleLeds(); // Everything ready lets give user some feedback by cycling leds } ///////////////////////////////////////// Main Loop /////////////////////////////////// void loop () { do { successRead = getID(); // sets successRead to 1 when we get read from reader otherwise 0 if (programMode) { cycleLeds(); // Program Mode cycles through RGB waiting to read a new card } else { normalModeOn(); // Normal mode, blue Power LED is on, all others are off } } while (!successRead); //the program will not go further while you not get a successful read if (programMode) { if ( isMaster(readCard) ) { //If master card scanned again exit program mode myGLCD.clrScr(); myGLCD.print("Programlama:", LEFT, 0); myGLCD.print("PROGRAMLAMA", CENTER, 16); myGLCD.print("KAPATILDI", CENTER, 24); delay(2500); myGLCD.clrScr(); myGLCD.print("CAVDIR MYO:", LEFT, 0); myGLCD.print("LUTFEN KARTI", CENTER, 16); myGLCD.print("OKUTUN", CENTER, 24); programMode = false; return; } else { if ( findID(readCard) ) { //If scanned card is known delete it myGLCD.clrScr(); myGLCD.print("Programlama:", LEFT, 0); myGLCD.print("KART", CENTER, 16); myGLCD.print("SILINDI", CENTER, 24); delay(1500); deleteID(readCard); } else { // If scanned card is not known add it myGLCD.clrScr(); myGLCD.print("Programlama:", LEFT, 0); myGLCD.print("KART", CENTER, 16); myGLCD.print("EKLENDI", CENTER, 24); delay(1500); writeID(readCard); } } } else { if ( isMaster(readCard) ) { // If scanned card’s ID matches Master Card’s ID enter program mode programMode = true; myGLCD.clrScr(); myGLCD.print("Programlama:", LEFT, 0); myGLCD.print("PROGRAMLAMA", CENTER, 16); myGLCD.print("ETKIN", CENTER, 24); delay(1500); myGLCD.clrScr(); myGLCD.print("Programlama:", LEFT, 0); myGLCD.print("LUTFEN KARTI", CENTER, 16); myGLCD.print("OKUTUN", CENTER, 24); } else { if ( findID(readCard) ) { // If not, see if the card is in the EEPROM myGLCD.clrScr(); myGLCD.print("CAVDIR MYO:", LEFT, 0); myGLCD.print("HOSGELDINIZ", CENTER, 24); openDoor(2000); myGLCD.clrScr(); myGLCD.print("CAVDIR MYO:", LEFT, 0); myGLCD.print("LUTFEN KARTI", CENTER, 16); myGLCD.print("OKUTUN", CENTER, 24); } else { // If not, show that the ID was not valid myGLCD.clrScr(); myGLCD.print("CAVDIR MYO:", LEFT, 0); myGLCD.print("ERISIM", CENTER, 16); myGLCD.print("REDDEDILDI", CENTER, 24); failed(); myGLCD.clrScr(); myGLCD.print("CAVDIR MYO:", LEFT, 0); myGLCD.print("LUTFEN KARTI", CENTER, 16); myGLCD.print("OKUTUN", CENTER, 24); } } } } ///////////////////////////////////////// Get PICC’s UID /////////////////////////////////// int 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 for (int 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; } ///////////////////////////////////////// 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 delay(200); 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 digitalWrite(greenLed, LED_OFF); // Make sure green LED is off delay(200); } //////////////////////////////////////// Normal Mode Led /////////////////////////////////// void normalModeOn () { digitalWrite(redLed, LED_OFF); // Make sure Red LED is off digitalWrite(greenLed, LED_OFF); // Make sure Green LED is off digitalWrite(relay, LOW); // Make sure Door is Locked } //////////////////////////////////////// Read an ID from EEPROM ////////////////////////////// void readID( int number ) { int start = (number * 4 ) + 2; // Figure out starting position for ( int 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! int num = EEPROM.read(0); // Get the numer of used spaces, position 0 stores the number of ID cards int 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 ( int 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(); } else { failedWrite(); } } ///////////////////////////////////////// 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 } else { int num = EEPROM.read(0); // Get the numer of used spaces, position 0 stores the number of ID cards int slot; // Figure out the slot number of the card int start;// = ( num * 4 ) + 6; // Figure out where the next slot starts int looping; // The number of times the loop repeats int j; int 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 ( int k = 0; k < 4; k++ ) { //Shifting loop EEPROM.write( start+j+k, 0); } successDelete(); } } ///////////////////////////////////////// Check Bytes /////////////////////////////////// boolean checkTwo ( byte a[], byte b[] ) { if ( a[0] != NULL ) // Make sure there is something in the array first match = true; // Assume they match at first for ( int k = 0; k < 4; k++ ) { // Loop 4 times if ( a[k] != b[k] ) // IF a != b then set match = false, one fails, all fail match = false; } if ( match ) { // Check to see if if match is still true return true; // Return true } else { return false; // Return false } } ///////////////////////////////////////// Find Slot /////////////////////////////////// int findIDSLOT( byte find[] ) { int count = EEPROM.read(0); // Read the first Byte of EEPROM that for ( int 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 break; // Stop looking we found it } } } ///////////////////////////////////////// Find ID From EEPROM /////////////////////////////////// boolean findID( byte find[] ) { int count = EEPROM.read(0); // Read the first Byte of EEPROM that for ( int 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; break; // Stop looking we found it } 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(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); //Serial.println("Succesfully added ID record to EEPROM"); } ///////////////////////////////////////// Write Failed to EEPROM /////////////////////////////////// // Flashes the red LED 3 times to indicate a failed write to EEPROM void failedWrite() { 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); //Serial.println("Failed! There is something wrong with ID or bad EEPROM"); } ///////////////////////////////////////// Success Remove UID From EEPROM /////////////////////////////////// // Flashes the blue LED 3 times to indicate a success delete to EEPROM void successDelete() { digitalWrite(redLed, LED_OFF); // Make sure red LED is off digitalWrite(greenLed, LED_OFF); // Make sure green LED is off } ////////////////////// Check readCard IF is masterCard /////////////////////////////////// // Check to see if the ID passed is the master programing card boolean isMaster( byte test[] ) { if ( checkTwo( test, masterCard ) ) return true; else return false; } ///////////////////////////////////////// Unlock Door /////////////////////////////////// void openDoor( int setDelay ) { digitalWrite(redLed, HIGH); // Turn off red LED digitalWrite(A5, HIGH); // Turn on green LED digitalWrite(relay, HIGH); // Unlock door! for (int i = 0; i < 12; i++){ // play welcome sound int access_noteDuration = 1000/access_noteDurations[i]; tone(buzzPin, access_melody[i],access_noteDuration); int access_pauseBetweenNotes = access_noteDuration * 1.30; delay(access_pauseBetweenNotes); noTone(buzzPin); } delay(setDelay); // Hold door lock open for given seconds digitalWrite(relay, HIGH); // Relock door digitalWrite(A5, LOW); // Turn on green LED delay(2000); // Hold green LED on for 2 more seconds } ///////////////////////////////////////// Failed Access /////////////////////////////////// void failed() { digitalWrite(greenLed, LED_OFF); // Make sure green LED is off digitalWrite(A2, HIGH); // Turn on red LED for (int i = 0; i < 6; i++){ // playa rejection sound int fail_noteDuration = 1000/fail_noteDurations[i]; tone(buzzPin, fail_melody[i],fail_noteDuration); int fail_pauseBetweenNotes = fail_noteDuration * 1.30; delay(fail_pauseBetweenNotes); noTone(buzzPin); } delay(1200); digitalWrite(A2, LOW); // Turn on red LED } [/php]