Arduino RFID

Voilà, je commence à utiliser la programmation de micro-controleur. Un Arduino UNO en l’occurrence. Je voulais voire comment fonctionnent les cartes RFID et leur programmation.

C'est un simple petit test où la carte 1 allume une LED bleue (la carte master), la 3 une LED verte (carte programmée et reconnue) et la 4 une rouge + un buzzer (la carte ne fait pas partie des cartes valide). À partir de maintenant, j'ai 3 niveaux de reconnaissance et je vais pouvoir en faire qq chose...

Affaire à suivre....

Code source

/**
  * RFID Access Control Single
  *
  * This project implements a single stand-alone RFID access control
  * system that can operate independently of a host computer or any
  * other device. It uses an RDM630 RFID reader module to
  * scan for 125KHz RFID tags, and when a recognised tag is identified
  * it toggles an output for a configurable duration, typically 2
  * seconds. The output can then be used to control anything.
  *
  * Some of this code was copy from Jonathan Oxer <jon@oxer.com.au>
  * http://www.practicalarduino.com/projects/medium/rfid-access-control
  */
//

#include <SoftwareSerial.h>
#include <LiquidCrystal.h>

// Set up the serial connection to the RFID reader module. In order to
// keep the Arduino TX and RX pins free for communication with a host,
// the sketch uses the SoftwareSerial library to implement serial
// communications on other pins.

#define rxPin 6
#define txPin 7
const int DISPLAY_TIME = 1000; // In milliseconds

// Create a software serial object for the connection to the RFID module
// and to the LCD display

SoftwareSerial rfid = SoftwareSerial( rxPin, txPin );
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// Specify how long the strike plate should be held open.
#define unlockSeconds 2

// The tag database consists of two parts. The first part is an array of
// tag values with each tag taking up 5 bytes. The second is a list of
// names with one name for each tag (ie: group of 5 bytes).
char* allowedTags[] = {
      "0000000000", // Tag 1
      "0000000000", // Tag 2
      "0000000000", // Tag 3
      "0000000000", // Tag 4
};

// List of names to associate with the matching tag IDs
char* tagName[] = {
      "User 1", // Tag 1
      "User 2", // Tag 2
      "User 3", // Tag 3
      "User 4", // Tag 4
};

// Check the number of tags defined
int numberOfTags = sizeof(allowedTags)/sizeof(allowedTags[0]);

int incomingByte = 0; // To store incoming serial data

/**
  * Setup
  */
void setup() {

      Serial.begin(9600); // Serial port for connection to host
      rfid.begin(9600); // Serial port for connection to RFID module

      Serial.println("RFID reader starting up");
      lcd.begin(16, 2);
}


/**
  * Fire the relay to activate the strike plate for the configured
  * number of seconds.
  */
void unlock() {

      delay(unlockSeconds * 1000);

}

/**
  * Search for a specific tag in the database
  */
int findTag( char tagValue[10] ) {
   for (int thisCard = 0; thisCard < numberOfTags; thisCard++) {
       // Check if the tag value matches this row in the tag database
       if(strcmp(tagValue, allowedTags[thisCard]) == 0) {
           // The row in the database starts at 0, so add 1 to the result so
           // that the card ID starts from 1 instead (0 represents "no match")
           return(thisCard + 1);
       }
   }
   // If we don't find the tag return a tag ID of 0 to show there was no match

   return(0);
}

/**
  * Loop
  */
void loop() {
    byte i = 0;
    byte val = 0;
    byte checksum = 0;
    byte bytesRead = 0;
    byte tempByte = 0;
    byte tagBytes[6]; // "Unique" tags are only 5 bytes but we need an extra byte for the checksum
    char tagValue[10];

    lcd.setCursor(0,0);
    lcd.print("Readytoread");
    lcd.setCursor(0,1);
    lcd.print("aRFIDcard");
    //ReadfromtheRFIDmodule.BecausethisconnectionusesSoftwareSerial
    //thereisnoequivalenttotheSerial.available()function,soatthis
    //pointtheprogramblockswhilewaitingforavaluefromthemodule
    if((val=rfid.read())==2){//Checkforheader
        bytesRead=0;
        while(bytesRead<12){//Read10digitcode+2digitchecksum
            val=rfid.read();

            //Appendthefirst10bytes(0to9)totherawtagvalue
            if(bytesRead<10)
            {
                tagValue[bytesRead]=val;
            }

            //Check if this is a header or stop byte before the 10 digit reading is complete
            if((val==0x0D)||(val==0x0A)||(val==0x03)||(val==0x02)){
                break;//Stopreading
            }

            //Ascii/Hexconversion:
            if((val>='0')&&(val<='9')){
                val=val-'0';
            } elseif((val>='A')&&(val<='F')){
                val=10+val-'A';
            }

            // Every two hex-digits, add a byte to the code:
            if(bytesRead & 1 == 1) {
                //Make space for this hex-digit by shifting the previous digit 4 bits to the left
                tagBytes[bytesRead >> 1] = (val| (tempByte<<4));

                if(bytesRead>>1!=5){//If
we'reatthechecksumbyte,
checksum^=
tagBytes[bytesRead
>>1];//
Calculatethechecksum...
(XOR)
};
}else{
tempByte=val;
//Storethe
firsthexdigit
first
};

bytesRead++;//Readytoreadnextdigit
}

//SendtheresulttothehostconnectedviaUSB
if(bytesRead==12){//12digitreadiscomplete
tagValue[10]='\0';//Null-terminatethestring

Serial.print("Tagread:");
for(i=0;i<5;i++){
//Addaleading0topadoutvaluesbelow
16
if(tagBytes[i]<16){
Serial.print("0");
}
Serial.print(tagBytes[i],HEX);
}
Serial.println();

Serial.print("Checksum:");
Serial.print(tagBytes[5],HEX);
Serial.println(tagBytes[5]==
checksum?"--
passed.":"--
error.");

//Showtherawtag
value
//Serial.print("VALUE:
");
//Serial.println(tagValue);

//Searchthetag
databaseforthisparticular
tag
inttagId=findTag(
tagValue);

//Onlyfirethestrike
plateifthistagwasfoundin
thedatabase
if(tagId>0)
{
Serial.print("Authorized
tag
ID
");
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Welcome
");
lcd.print(tagName[tagId
-
1]);
Serial.print(tagId);
Serial.print(":
unlocking
for
");
Serial.println(tagName[tagId
-
1]);
//
Get
the
name
for
this
tag
from
the
database
lcd.setCursor(0,1);
lcd.print("door
unlocked");
unlock();
//
Fire
the
strike
plate
to
open
the
lock
}
else{
Serial.println("Tag
not
authorized");
lcd.setCursor(0,0);
lcd.print("This
card
is
not
");
lcd.setCursor(0,1);
lcd.print("an
autorised
one");
delay(1000);
}
Serial.println();//
Blankseparatorlinein
output
}

bytesRead=0;
}
}
/*------------------------------------------------------------------
  This is a sample code for RDM630 RFID reader by Spekel(Spekel.se)
  This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
  http://creativecommons.org/licenses/by-nc-sa/3.0/
  -------------------------------------------------------------------*/
#include <SoftwareSerial.h>

#define rxPin 2
#define txPin 3
#define ARR_LEN 8

const int DISPLAY_TIME = 100; // In milliseconds

const int switchPin = 8;
const int redLedPin = 9;
const int greenLedPin = 10;
const int blueLedPin = 11;
const int buzzerPin = 12;

int red = 0;
int green = 1;
int blue = 2;


int redIntensity = 0;
int greenIntensity = 0;
int blueIntensity = 0;

char code[20];
int val = 0;
int bytesread = 0;
String masterTag = "0100C1A6B3@5";
String targetTag[ARR_LEN] = { "0100C216B500" , "0100C201E567" } ;//, "0100C20086K5" , "0100C18E89CL" };

//------------------------------------
//create a Serial object RFID
SoftwareSerial RFID= SoftwareSerial(rxPin, txPin);






void setup(){
      Serial.begin(9600);
        Serial.println("Serial Ready");
          RFID.begin(9600);
            Serial.println("RFID Ready");
              pinMode(rxPin, INPUT);
                pinMode(txPin, OUTPUT);
                  pinMode(buzzerPin, OUTPUT);
                    pinMode(switchPin, INPUT);  //pinMode(ledPin, OUTPUT);
}


void loop(){

      delay(2000);

        if(digitalRead(switchPin) == 1){

                do{
                          delay(1000);
                                String readedTag = readCard();   //    read 12 digit code
                                      if(readedTag != "none" ){                // if 12 digit read is complete
                                            boolean stateTag = testTag(readedTag);
                                                if(stateTag){
                                                          Serial.println("l'alarm est deconnéctée pendant 5s");
                                                              //delay(5000);
                                                              break;
                                                                }
                                                      }

                                            Serial.println("la porte est sous alarm ------------!");
                                                } while(digitalRead(switchPin) == 1);

                    if(digitalRead(switchPin) == 0){
                              alarm();
                                  }
                  } else {
                          Serial.println("la porte est ouverte ce n'est pas la peine de s'ammorcer ! ");
                            }

}

boolean card(){

}

boolean testTag(String tag){
      boolean validCard = false;
        if(tag == masterTag){
                Serial.println("ok master Tag reconnu -------------!!!!");
                    signal(blue);
                        validCard = true;
                          }

          for( int i = 0 ; i < ARR_LEN ; i++ ){
                  if( tag == targetTag[i] ){
                            signal(green);
                                  validCard = true;
                                        //Serial.println("ok Tag reconnu !");
                                        delay( 100 );
                                              break;
                                                  }
                    }
            if(validCard != true ) {
                    Serial.println("Tag non reconnu !");
                          signal(red);
                              }
              return validCard;
}


String readCard(){
      val = 0;
        bytesread = 0;
          int readyToRead = 0;

            while(bytesread < 12) {
                    val = RFID.read();
                        if(val == 3) { // if header or stop bytes before the 10 digit reading
                                  break; // stop reading
                                      }

                            if(val != 2) {
                                      code[bytesread] = val; // add the digit
                                            bytesread++; // ready to read next digit
                                                  code[bytesread] = '\0'; // add the NULL
                                                        if(val != -1) {
                                                                readyToRead++;
                                                                      }
                                                            }
                              }
              //debugTag();
              String tag = code;    // Maintenant on a une chaine de caractère plus facile à tester
                if(bytesread >= 12 && readyToRead == 12){
                        return tag;
                          } else {
                                  tag = "none";
                                      return tag;
                                        }
}





void signal(int color){

      int colorLed[] = { redLedPin , greenLedPin , blueLedPin };
        analogWrite(colorLed[color], greenIntensity <= 255);
          if (color == 0 ) {
                  for (long i = 0 ; i < 20000L ; i += 3038 ) {
                            digitalWrite(buzzerPin , HIGH);
                                  delayMicroseconds(1519);
                                        digitalWrite(buzzerPin , LOW);
                                              delayMicroseconds(1519);
                                                  }
                    } else {
                            delay(DISPLAY_TIME);
                              }
            analogWrite(colorLed[color], LOW);
              delay(DISPLAY_TIME);

}


void alarm(){

    for (int i = 0; i < 10; ++i)
          {
                  for (long j = 0 ; j < 700000L ; j += 3038 ) {
                          digitalWrite(buzzerPin , HIGH);
                              delayMicroseconds(1519);
                                  digitalWrite(buzzerPin , LOW);
                                      delayMicroseconds(1519);
                                          }
                      delay(500);
                          Serial.println("!!!!!!!!!!!!!---------------ALARM-----------------!!!!!!!!!!!!!!!!!");
                              String readedTag = readCard();   //    read 12 digit code
                                  if(readedTag != "none" ){                // if 12 digit read is complete
                                            boolean stateTag = testTag(readedTag);
                                                  if(stateTag){
                                                        Serial.println("Carte détéctée.........j'arrête l'alarm !");
                                                            break;
                                                                  }
                                                      }
                                    }
}

Written by sinux in electronics on Sun 04 March 2012. Tags: microcontroller, rfid, hacking, electronics,