Esp8266-201 and rc522

hello there!i m trying this post,to connect esp8266-201 and rc522 rfid reader and also connect esp to cayenne.until now i ve tried this code.

[code]#include <ESP8266WiFi.h>
#include <SPI.h>
#include <BlynkSimpleEsp8266.h>
#include “CayenneDefines.h”
#include “CayenneWiFiClient.h”"
#include “MFRC522.h”

#define RST_PIN 15 // RST-PIN für RC522 - RFID - SPI - Modul GPIO15
#define SS_PIN 2 // SDA-PIN für RC522 - RFID - SPI - Modul GPIO2

// Cayenne authentication token. This should be obtained from the Cayenne Dashboard.
char token = “”;
// Your network name and password.
char ssid = “”;
char password = “”;

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance

void setup() {

SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522

Cayenne.begin(token, ssid, password);

}

void loop() {
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent()) {
delay(50);
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
delay(50);
return;
}
// Dump debug info about the card; PICC_HaltA() is automatically called
mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}[/code]
my problem is that if i read the code correctly it scans for a new card every time.i just want to add 2 cards and check if any of them was readed by the rfid reader,so it would make high or low 2 other pins,informing me for presence,like this code on this post (which i m trying to make)

[code]#include <SoftwareSerial.h> //SoftwareSerial library required for Arduino communication with the Grove RFID reader and the Grove Serial MP3 player
#include <BlynkSimpleEsp8266.h>
#include “CayenneDefines.h”
#include “CayenneWiFiClient.h”
// Cayenne authentication token. This should be obtained from the Cayenne Dashboard.
char token = “”;
// Your network name and password.
char ssid = “”;
char password = “”;

SoftwareSerial mp3(2,3); //Grove Serial MP3 Player is connected to Digital Pins 2 and 3
SoftwareSerial rfid(10,11); //Grove 125kHz RFID reader is connected to Digital Pins 10 and 11 (Note: lower pins may not work with this board)

//Global Variables
int rfidValue = 0; //rfidValue: used to store the value obtained from the RFID tag
int vPin6 = 0; //vPin6: is associated with Virtual Pin 6 on the Cayenne Dashboard - activated when a person is detected by the sensors.
int vPin7 = 0; //vPin7: is associated with Virtual Pin 7 on the Cayenne Dashboard - activated when the person fails to identify themselves.
unsigned long start_Time; //start_Time: is used in various time related events (logs the start time)
unsigned long stop_Time; //stop_Time: is used in various time related events (logs the stop time)
unsigned long time_Diff = 0; //time_Diff: is used in various time related events (is used to record the time elapsed from start time to stop time)
boolean keyMessagePlayed=false; //keyMessagePlayed: helps to prevent a message from replaying repeatedly when a person is detected.
boolean waitingForKey = true; //waitingForKey: is used to identify if we are still waiting for a person to present a valid key or not
int songNumber = -1; //songNumber is a variable used to hold the song number to play (from the playlist on the SD card on the MP3 player)

/*===============================setup()============================================================================================================================= */
void setup(){
delay(2500); //Delay for 2.5 seconds to allow the Grove MP3 player to initialise
mp3.begin(9600); //Establish a communication link with the Grove MP3 player
rfid.begin(9600); //Establish a communication link with the Grove 125 kHz RFID reader

Cayenne.begin(token, ssid, password); //Establish a communication link with the Cayenne Server - the token must match that in the Cayenne Dashboard
setVolume(28); //Set the volume of the MP3 player to 28 (Range = 0 to 31, whereby 31 is maximum volume)
setPlayMode(0x00); //Configure the MP3 player to play the MP3 file ONCE only (per request).
}

/*===============================loop()============================================================================================================================= */
void loop(){
Cayenne.run(); //Synchronise with the Cayenne Server

if(vPin6&&!vPin7){ //Only progress if Virtual Pin 6 (Person detection) is ACTIVATED but ONLY when Virtual Pin 7 (Intruder alert) has NOT already been activated.
if(!keyMessagePlayed){ //This ensures that the message is played only ONCE when a person has been detected.
playSong(1); //Play the following message on the Grove MP3 player: “Place your keys on the mat”
keyMessagePlayed=true; //keyMessagePlayed is changed to TRUE once the message has been played.
}

 /*This section requests the Arduino to look out for the person's keys, and returns TRUE when a successful identification is made.
  * It returns FALSE if the person fails to put their keys on the Mat within 10 seconds , OR if the person cannot be identified by the Arduino (e.g. Wrong code)
  * If a person has been successfully identified/verified, it will play a welcome message, and switch off the "Person Detection Trigger", which will then 
  * be used as a method to switch off the Security scanning process.
  * If a person fails to be identified within 10 seconds, the person is notified that they have been detected, and an Alarm will sound.
  * Virtual Pin 7 (Intruder Alert) will be ACTIVATED - which will be used as a Trigger within Cayenne to notify me of an Intruder (via Email or SMS).
  */
if(listenForKeys()){                                 
  //TRUE = Person Identified within 10 seconds
  playSong(songNumber);                               //Play message "Welcome Home - Scott"
  vPin6 = 0;                                          //Deactivate the "Person Detection" virtual pin (6).
  keyMessagePlayed=false;                             //Reset the keyMessagePlayed variable for future detections.
} else {
  //FALSE = Person not identified within 10 seconds
  playSong(2);                                        //Play message on Grove MP3 player : "Your presence has been detected"
  delay(4000);                                        //A FOUR second delay is required to allow the message to play, before the alarm sounds.
  playSong(3);                                        //Sound the ALARM by playing song 2 on the Grove MP3 player. Song numbers are determined by the order they have been written to the SD card.
  delay(8000);                                        //An EIGHT second delay allows the alarm to sound for 8 seconds.
  playSong(99);                                       //Playing a non-existing track essentially STOPS the MP3 player.
  vPin7=1;                                            //ACTIVATE Virtual Pin 7 - Intruder Detected
  keyMessagePlayed=false;                             //Reset the keyMessagePlayed variable for future detections.
}

upDateCayenne();                                      //Update the Cayenne Dashboard with any changes made to the virtual pins (6 or 7). This method can be found below.

}
}

/*=writeToMP3 function======================================================================================================================================================

  • is used to simplify the process of sending commands to the Grove MP3 player
    */
    void writeToMP3(byte MsgLEN, byte A, byte B, byte C, byte D, byte E, byte F){
    byte codeMsg = {MsgLEN, A,B,C,D,E,F};
    mp3.write(0x7E); //Start Code for every command = 0x7E
    for(byte i = 0; i<MsgLEN+1; i++){
    mp3.write(codeMsg[i]); //Send the rest of the command to the GROVE MP3 player
    }
    }

/*=setVolume function======================================================================================================================================================

  • is used to simplify the process of setting the Volume on the Grove MP3 player
  • Volume range = 00 (muted) to 31 (max volume)
    */
    void setVolume(byte Volume){
    byte tempVol = constrain(Volume, 0, 31); //Ensure the Volume does not extend beyond the MP3 player’s limits
    writeToMP3(0x03, 0xA7, tempVol, 0x7E, 0x00, 0x00, 0x00);
    }

/*=setPlayMode function======================================================================================================================================================

  • is used to simplify the process of setting up the play Mode on the Grove MP3 player
  • playMode options:
  •  0x00 = Single song - played only once ie. not repeated.  (default)
    
  •  0x01 = Single song - cycled ie. repeats over and over.
    
  •  0x02 = All songs - cycled 
    
  •  0x03 = play songs randomly   
    

*/
void setPlayMode(byte playMode){
writeToMP3(0x03, 0xA9, playMode, 0x7E, 0x00, 0x00, 0x00);
}

/*=playSong function======================================================================================================================================================

  • is used to simplify the process of playing a specific track on the SD card of the Grove MP3 player.
  • The track number is determined by the order in which the songs were written to the SD card.
  • Best to name the tracks in sequence, e.g. 0000_Song0.mp3 , 0001_Song1.mp3 etc etc.
  • And also best to copy them one by one to the SD card from Song 0 to Song x.
    */
    void playSong(byte songNum){
    writeToMP3(0x04, 0xA0, 0x00, songNum, 0x7E, 0x00, 0x00);
    }

/*=listenForKeys function======================================================================================================================================================

  • is used to identify the person detected.
  • The Arduino will wait a maximum of 10 seconds for the person to place their RFID tag near the Grove RFID reader antenna.
  • This example shows two RFID tag values that will be accepted.
  • This method also prints the RFID tag value to the Serial monitor - for debugging purposes.
    */
    boolean listenForKeys(){
    //reset some variables every time this function is called.
    songNumber = -1;
    start_Time = millis();
    time_Diff = 0;
    waitingForKey = true;
    rfidValue=0;

//Wait for a valid RFID tag for a maximum of 10 seconds
while(time_Diff<10000 && waitingForKey){
Cayenne.run(); //Make sure to stay in contact with the Cayenne Server while waiting for the RFID tag.
stop_Time = millis();
time_Diff = stop_Time - start_Time; //Measure the time elapsed.

 //If an RFID tag is detected by the Grove RFID reader, it will transmit a series of numbers related to the Tag ID.
 if(rfid.available()){
    while(rfid.available()){                          //Make sure to read all of the numbers transmitted by the Grove RFID reader
      rfidValue += rfid.read();                       //You could employ a method to extract the exact RFID Tag ID - however just adding each number received -  produced a unique number that I could use to identify the person.
      delay(1);                                       //A small delay between reads - ensures you get all of the numbers from the RFID reader in one go.
    }
    Serial.println("RFID VALUE:");
    Serial.println(rfidValue);                        //Print the Unique RFID Tag value to the Serial monitor - useful for debugging

    
    //If a person has an RFID tag that can be identified in this list, then play a personalised message for that person.
    switch(rfidValue){
      case 628:                                       //Person #1 has a Tag that generates an rfidValue of 628.
        songNumber=4;                                 //File#4 (or message number 4) on the Grove MP3 player will be played when this person is detected.
        waitingForKey = false;                        //setting the "waitingForKey" variable to FALSE - will allow us to break out of the while loop (instead of waiting for a full 10 seconds).
        break;
      case 651:                                       //Person #2 has a Tag that generates an rfidValue of 651.
        songNumber=5;                                 //File#5 (or message number 5) on the Grove MP3 player will be played when this person is detected.
        waitingForKey = false;                        //setting the "waitingForKey" variable to FALSE - will allow us to break out of the while loop (instead of waiting for a full 10 seconds).
        break;
      case 694:                                       //Person #3 has a Tag that generates an rfidValue of 694.
        songNumber=6;                                 //File#6 (or message number 6) on the Grove MP3 player will be played when this person is detected.
        waitingForKey = false;                        //setting the "waitingForKey" variable to FALSE - will allow us to break out of the while loop (instead of waiting for a full 10 seconds).
        break;
      case 658:                                       //Person #4 has a Tag that generates an rfidValue of 658.
        songNumber=7;                                 //File#7 (or message number 7) on the Grove MP3 player will be played when this person is detected.
        waitingForKey = false;                        //setting the "waitingForKey" variable to FALSE - will allow us to break out of the while loop (instead of waiting for a full 10 seconds).
        break;
      case 677:                                       //Person #5 has a Tag that generates an rfidValue of 677.
        songNumber=8;                                 //File#8 (or message number 8) on the Grove MP3 player will be played when this person is detected.
        waitingForKey = false;                        //setting the "waitingForKey" variable to FALSE - will allow us to break out of the while loop (instead of waiting for a full 10 seconds).
        break;
      default:
        waitingForKey = true;                         //If a person has not been identified, keep waiting for the key/tag until the times runs out.
        break;
    }
}

}

/* If we are still waiting for an RFID tag (key) at this point, then we were unsuccessful in identifying the person within 10 seconds.

  • Returning FALSE - will sound the alarm, and will activate Virtual Pin 7 (Intruder Alert).
  • Returning TRUE - means that we have identified the person who triggered the sensors, and can therefore relax, and turn OFF the Security sensors.
    */
    if(waitingForKey){
    return false;
    } else {
    return true;
    }
    }[/code]
    without having to play,or write to mp3.just check for the cards and activate pins.
    any help on that?any ideas??

Hi @k.aggelopoulos,

Welcome to the Cayenne community. Thanks for posting your code too.

I think @kreggly, @ats1080s1, or @rsiegel would be much more equipped to help you than I would be. :slight_smile:

If you can get this working, do you think you can create a video of it working? And also submit it to the Cayenne project submission contest. RFID is a definite contender for the $200 prize!

Please keep us updated with this, I will be following this project!

-B

Howdy, @k.aggelopoulos

So if I understand correctly, what you want to do is read a card and if the card matches a pre-programmed number, then set some bits.

So what I would do, just taking a brief look, is take your UID data stored in mfrc522.uid and convert it to a string like in the example shown here

Then you can do a string compare with a local constant string to determine to set the bits or not.

Cheers,

Craig

I had this bookmarked to order a rc522 and then never did… It’s on its way now!

sorry to reply so late,but i was on holidays!i ll try the solution provided in the morning and i 'll get back!
Really thanks for your time and your advices!!

1 Like

I got mine soldered up, let me know how you make out! I’ll trying it on mine right now.

Ok, so I think this should give you everything you want. The first thing I noticed is that the example (and your code) uses pin 15 which is ok but 15 has to be grounded to boot the esp which makes it a pain to use. I would suggest leaving pin 15 grounded and changing the RST pin to gpio 0. Second thing is it constantly scans the card if the card is in front of it and causes the ESP to crash after 10 seconds or so. I’m not sure the exact cause, maybe someone else can chime in, but running loops that run for a long time (long being 5-10 seconds) will crash the ESP. Anyway, I found an instructable that gives you the card number and just used that code to send it to the dashboard.

//#define CAYENNE_DEBUG         // Uncomment to show debug messages
#define CAYENNE_PRINT Serial  // Comment this out to disable prints and save space
#include "CayenneDefines.h"
#include "BlynkSimpleEsp8266.h"
#include "CayenneWiFiClient.h"
#include <SPI.h>
#include "MFRC522.h"

//Pins for RC522
#define RST_PIN 0
#define SS_PIN 2 //SDA

// Cayenne authentication token. This should be obtained from the Cayenne Dashboard.
char token[] = "TOKEN";
// Your network name and password.
char ssid[] = "SSID";
char password[] = "PASSWORD";

//Set optional pins
const int PIEZO_PIN = 4;
const int LED_PIN = 5;

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance

void setup() {
  Serial.begin(9600); // Initialize serial communications
  delay(250);
  Serial.print("Setup");
  Cayenne.begin(token, ssid, password);

  SPI.begin(); // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522

  pinMode(PIEZO_PIN,OUTPUT);
  pinMode(LED_PIN,OUTPUT);
}

void loop() {
  // Look for new cards
  if(mfrc522.PICC_IsNewCardPresent()) {
    unsigned long uid = getID();
    //Check if card is valid
    if(uid != -1){
      //Print UID to serial
      Serial.print("Card detected, UID: "); Serial.println(uid);
      
      //Send UID to Cayenne via Virtual Pin 0
      Cayenne.virtualWrite(V0, uid);
      
      //Optional - play a tone for 1/2 second
      tone(PIEZO_PIN, 100, 500);
      
      //Optional - light an LED for 1/2 second
      digitalWrite(LED_PIN, HIGH);
      delay(500);
      digitalWrite(LED_PIN, LOW);
    }
  }

  //Run Cayenne Functions
  Cayenne.run();
}

unsigned long getID(){
  if ( ! mfrc522.PICC_ReadCardSerial()) { //Since a PICC placed get Serial and continue
    return -1;
  }
  unsigned long hex_num;
  hex_num =  mfrc522.uid.uidByte[0] << 24;
  hex_num += mfrc522.uid.uidByte[1] << 16;
  hex_num += mfrc522.uid.uidByte[2] <<  8;
  hex_num += mfrc522.uid.uidByte[3];
  mfrc522.PICC_HaltA(); // Stop reading
  return hex_num;
}

By the way, you can even scan smartphones with NFC with this thing! Lots of possibilities, thanks for bringing it to my attention!

Hi @adam / @rsiegel / @kreggly,

This is really helpful code, I am trying to take this a bit forward to use 1 card to switch on all lights and the other to switch off all lights using Cayenne of course. The code provided reads the card and simply sends the id to cayenne, not not being able to make use of it to perform any action.

Can I get some help as to how do I assign unique cards to it and make each card perform a certain task using triggers.

Any help would be most appreciated.

Thanks

Hi @soubir,

If you are using the code @adam provided, then you should be able to do triggers on V0 and make triggers like this:

if V0 equals card_number then do something cool.

Give it a try and let us know.

Cheers,

Craig

3 Likes

Hi @kreggly,

I am using Adam’s code.

On my serial port i can see the uids, on my cayenne dashboard i can see the uids change with different tags, but how do i setup the trigger… what kind of widget should i use where i can enter numbers as a part of the trigger… i tried all sorts , couldn’t find any.

Please help.

Thanks
S

Hi @kreggly , @adam

Any help on this … please …

Cheers

Something like this should work. Can’t test it right now, let me know if it doesn’t.

Hi @adam,

Thank you so much for the suggestion. I have managed to setup up the trigger and get it to “somewhat” working. My UIDs are 10 digit long , sometimes the triggers are working but 98% of the times its not. The dashboard immediately shows the updated value. If the triggers work, thats after 2 mins of tapping the card.

Also, I have configured this using a ESP8266.

Any suggestions. Really appreciate your help.

Thanks
S

@rob, are triggers working currently?

Cheers,

Craig

Hi @adam, @kreggly, @rob

Any light, any hope ? In general my other triggers are also inconsistent on Arduino, are these related ?

My RFID triggers are sometimes working but at a delay of around 2 mins.

Thanks

I have no info for you @soubir

There were some trigger improvements in a release a month ago, but not in the one yesterday as far as I can tell. You may try deleting your triggers and creating them again and see if you get better performance.

Craig