NFC Shield inconsistency with reading tags

Adafruit Ethernet, Motor, Proto, Wave, Datalogger, GPS Shields - etc!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
Maiu_bm
 
Posts: 5
Joined: Thu Aug 14, 2014 5:20 am

NFC Shield inconsistency with reading tags

Post by Maiu_bm »

Hey, i have a project in which i am integrating a NFC Shield with a WIFI Arduino Shield and an Arduino Uno R3. The program read the tag and send it to mysql using a php script. The problem is that i make a conversion from the tag hex to int and then to string. I am testing with 2 cards but the readings change all the time. If i try to send the hexanumber then it to much and send blank information. The values should be 304 and 637
What can i do?

Code: Select all

//wifi libraries
#include <SPI.h>
#include <WiFi.h>
//NFC-Libs
#include <Wire.h>
#include <Adafruit_NFCShield_I2C.h>

#define IRQ   (2)
#define RESET (3)  // Not connected by default on the NFC Shield
   
Adafruit_NFCShield_I2C nfc(IRQ, RESET);

char ssid[] = "";     //  your network SSID (name) 
char pass[] = "";  // your network password
int status = WL_IDLE_STATUS;

// Initialize the Wifi client library
WiFiClient client;
// server address:
//char server[] = "www.arduino.cc";
IPAddress server(192,xxx,xxx,xxx);  // numeric IP for laptop with server xamp installed (no DNS)

// What page to grab!
#define WEBSITE      "192,xxx,xxx,xxx"  // need to enter actual IP
#define WEBPAGE     "/PhpProjectThesis/add_data.php"

/*
//define Arduino pins to operate status LEDs
  const int signalPin = 8;
  const int failPin = 7;
  const int logUser = 6;
  const int logKiste = 5;*/
//this is the counter that will be used for uploading data
  long pollCounter = 1; 

//used for storing data for upload
//set it to the data type that suits your data
int id;
int im_type = 1; // 1 stands for RFID to Log In in the Checkin-DB, 2 stands for LogOut
int sublocation = 4; //set location key according to where the RFID reader is installed, e.g. 4 for Office 4

//used for data received from base station
int
  command_1, command_2;
  
//variables for poll timer
//this is a 'non-blocking' timer -- does not use delay(), so operations such as sensor reads can continue between polls

//interval at which to poll base station
//takes a value in seconds; add more multipliers if you want a more convenient unit
  long pollInterval = 10L * 1000L;  //converts from millis; initial default value is to poll every 10 sec
  long lastPoll;                     //stores the last time we polled
  boolean pollFlag = false;          //tells the sketch whether to poll or not
//declare a variable to hold a numeric IP address
//can be overridden below if you use lookup
  void setup(void)
{
  /*set the LEDs
  pinMode(signalPin, OUTPUT);
  pinMode(failPin, OUTPUT);
  
   pinMode(logUser, OUTPUT);
  pinMode(logKiste, OUTPUT);
  
  //turn on the signal LED to show we're starting
  digitalWrite(signalPin, HIGH);
  
  //flash LEDs to confirm it works
  digitalWrite(failPin, HIGH);
  delay(200);
  digitalWrite(failPin, LOW);
  
  digitalWrite(logUser, HIGH);
  delay(200);
  digitalWrite(logKiste, LOW);
  
   digitalWrite(logUser, HIGH);
  delay(200);
  digitalWrite(logKiste, LOW);*/
    
  Serial.begin(115200);
  Serial.println(F("Hello, Beginning!\n")); 

  /* Initialise the module */
  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
   // digitalWrite(failPin, HIGH);  //turn on the fail LED
    Serial.println(F("WiFi shield not present")); 
    // don't continue:
    while(true);
  } 
  // attempt to connect to Wifi network:
  while ( status != WL_CONNECTED) { 
    Serial.println(F("Attempting to connect to SSID: "));
    Serial.println(ssid);
    // Connect to WPA/WPA2 network.   
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  } 
  // you're connected now, so print out the status:
  printWifiStatus();
  //flash the LED
  /*for (int i=0; i<5; i++)  {
  digitalWrite(signalPin, HIGH);
  delay(200);
  digitalWrite(signalPin, LOW);
  delay(200);  
  }*/
  if (!WiFi.begin(ssid, pass))
    {
      //digitalWrite(failPin, HIGH);  //turn on the fail LED
      Serial.println(F("Couldn't begin()! Check your wiring?"));
      while(true);
    }

	//Set up the NFC module
      Serial.println(F("Starting NF-Reader..."));
  
      nfc.begin();
          
      uint32_t versiondata = nfc.getFirmwareVersion();
      if (! versiondata) {
        Serial.print(F("Didn't find PN53x board"));
        while (true); // halt
      }
      // Got ok data, print it out!
      Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX); 
      Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC); 
      Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
            
      // configure board to read RFID tags
      nfc.SAMConfig();
      
      Serial.println(F("NF-Reader started!"));
	  //flash the LED 
		/*for (int i=0; i<5; i++)  {
		digitalWrite(signalPin, HIGH);
		delay(200);
		digitalWrite(signalPin, LOW);
		delay(200); */
      
      //Text for User to see system is ready
      Serial.println(F("Waiting for an ISO14443A Card ..."));
   // }
}  

void loop(void)
{
   //digitalWrite(signalPin, LOW);  //turn off the signal LED

  //check if it is time to poll
  if(pollFlag == true)
  
  {
  
      Serial.println();
      Serial.print("Poll counter: "); Serial.println(pollCounter);
      
      //execute our data handlers to get data to send back to base station
	 NFC_ID_handler();
	            
      //build the URI and GET args
      //we have to do this within the loop to get fresh values for data
      String url_base = WEBPAGE;   
              String url_param1 = "?id=" + String(id);
              String url_param2 = "&im_type=" + String(im_type);
              String url_param3 = "&sublo=" + String(sublocation);
              String url_httptail = " HTTP/1.0";
              String url_complete = url_base + url_param1 + url_param2 + url_param3 + url_httptail;
              Serial.println("url: " + url_complete);
               
         //String pageValue = connectAndRead(url_complete); //connect to the server and read the output
         //Serial.println(pageValue); //print out the findings.
      
      /* Try connecting to the website */
      
      if (client.connect(server, 80)) {
        Serial.println("connecting...");
        //digitalWrite(signalPin, HIGH);  //turn on the signal LED to show we're connected
        client.print("GET ");
        client.println(url_complete);
        client.println();
        client.print(F("Host: ")); client.print(F(WEBSITE)); client.print(F("\n"));
        client.print(F("Connection: close\n"));
        client.print(F("\n"));
        client.println();
        //digitalWrite(failPin, LOW);    //make sure fail LED is off after successful poll
      } else {
        Serial.println(F("Connection failed"));
        //digitalWrite(failPin, HIGH);  //turn fail LED on after unsuccessful poll
        return;
      }
    
      //define a String to hold our json object
      String commands = "";
      //set a flag for when to start adding to String
      boolean readflag = false;
      
      //read in data one character at a time while connected    
         while (client.available() && status == WL_CONNECTED) {
         char c = client.read();
         
         //start storing at the [ marker
         if (c=='[') {readflag = true;}
         if (c==']') {readflag = false;}
         //build data read from  client into a String
         if ((readflag == true) && (c != '['))  {
          commands = commands + c;
         }
         
        }
      
       client.flush();
       client.stop();
      //digitalWrite(signalPin, LOW);  //turn off the LED
       
        
      //now we should have all our commands in the String 'commands'
      //next we need to parse it into three separate integers
      //find out where the commas are
      int comma1 = commands.indexOf(',');
      int comma2 = commands.lastIndexOf(',');
    
      command_1 = (commands.substring(0,comma1)).toInt();
      command_2 = (commands.substring(comma1+1,comma2)).toInt();
            
      Serial.print(("\r\nRESULTS:\r\n  command_1: "));
      Serial.println(command_1);
      Serial.print(("  command_2: "));
      Serial.println(command_2);
            
      //execute our command handlers to process commands we received from the base station
      command_1_handler();
      command_2_handler();
            
      //now that we've polled, get ready for next poll
      pollCounter = pollCounter + 1;  //increment the counter
      pollFlag = false;
      lastPoll = millis();
      Serial.print("\r\n Next poll in ");
      Serial.println(pollInterval/1000);
  }  //end of what we do if pollFlag == true
  
  else  //what we do if pollFlag == false
  {
    
    //check to see if it's time to poll
    if (millis() >= (lastPoll + pollInterval))
     { //it's time to poll!
     pollFlag = true;
     }
     
  }  //end of what we do if pollFlag == false  
     
     
}  //end of the loop


/**************************************************************************/
/*!
    @brief  Tries to read the IP address and other connection details
*/
/**************************************************************************/
void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}
/**************************************************************************/
    /*!
        @brief  NFC-Reader is reading TAGs here
    */
    /**************************************************************************/
    
    void NFC_ID_handler(void)
    {
       uint8_t success;
       uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
       uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
            
       // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
       // 'uid' will be populated with the UID, and uidLength will indicate
       // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
            
       success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
       Serial.print("Success: "); Serial.println(success);
       id=0;
       for (int i = 0; i < 8; i++) {          //iterate over array, take value and write to ID_final as an integer
         id = id + uid[i];
       }
             
        // Display some basic information about the card
        Serial.println("Found an ISO14443A card");
        Serial.print("  UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
        Serial.print("  UID Value: ");
        nfc.PrintHex(uid, uidLength);
        Serial.println("");
        
        Serial.print("UID_final: "); Serial.println(id);
        
        if (uidLength == 4)
        {
          // We probably have a Mifare Classic card ... 
          Serial.println("Seems to be a Mifare Classic card (4 byte UID)");
    	  
          // Now we need to try to authenticate it for read/write access
          // Try with the factory default KeyA: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
          //Serial.println("Trying to authenticate block 4 with default KeyA value");
          uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
    	  
    	  // Start with block 4 (the first block of sector 1) since sector 0
    	  // contains the manufacturer data and it's probably better just
    	  // to leave it alone unless you know what you're doing
          success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, 4, 0, keya);
    	  
          if (success)
          {
            //Serial.println("Sector 1 (Blocks 4..7) has been authenticated");
            uint8_t data[16];
    		 // If you want to write something to block 4 to test with, uncomment
    		// the following line and this text should be read back in a minute
            // data = { 'a', 'd', 'a', 'f', 'r', 'u', 'i', 't', '.', 'c', 'o', 'm', 0, 0, 0, 0};
            // success = nfc.mifareclassic_WriteDataBlock (4, data);
    
            // Try to read the contents of block 4
            success = nfc.mifareclassic_ReadDataBlock(4, data);
    		
            if (success)
            {
              // Data seems to have been read ... spit it out
                Serial.println("Reading Block 4:");
                nfc.PrintHexChar(data, 16);
                Serial.println("");
    		  
              // Wait a bit before reading the card again
              delay(1000);
              pollFlag = true;
            }
            else
            {
              Serial.println("Ooops ... unable to read the requested block.  Try another key?");
			  
            }
          }
          else
          {
            Serial.println("Ooops ... authentication failed: Try another key?");
		
          }
        }
        if (uidLength == 7)
    {
      // We probably have a Mifare Ultralight card ...
      Serial.println("Seems to be a Mifare Ultralight tag (7 byte UID)");
    
      // Try to read the first general-purpose user page (#4)
      Serial.println("Reading page 4");
      uint8_t data[32];
      success = nfc.mifareultralight_ReadPage (4, data);
      if (success)
      {
        // Data seems to have been read ... spit it out
        nfc.PrintHexChar(data, 4);
        Serial.println("");
        // Wait a bit before reading the card again
              delay(1000);
              pollFlag = true;
    
        }
      else
      {
        Serial.println("Ooops ... unable to read the requested page!?");
      }
    }
}
	  

          void command_1_handler(void)
		{
			//example
			if (command_1 == 1)
				{
				 //log in user
				 //flash the LED 
				/*for (int i=0; i<5; i++)  {
				digitalWrite(logUser, HIGH);
				delay(200);
				digitalWrite(logUser, LOW);
				delay(200); 
				}*/
			}
		else if (command_1 == -1)
			{
				//Not registered or logged
				//flash the LED 
				/*for (int i=0; i<5; i++)  {
				digitalWrite(failPin, HIGH);
				delay(200);
				digitalWrite(failPin, LOW);
				delay(200); 
				} */
			}
		}
  void command_2_handler(void)
  {
        //example
		if (command_2 == 1)
		{
			 //log in kiste
			 //flash the LED 
			/*for (int i=0; i<5; i++)  {
			digitalWrite(logKiste, HIGH);
			delay(200);
			digitalWrite(logKiste, LOW);
			delay(200); 
			}*/
		}
		else if (command_2 == -1)
		{
			//Not registered or logged
			//flash the LED 
			/*for (int i=0; i<5; i++)  {
			digitalWrite(failPin, HIGH);
			delay(200);
			digitalWrite(failPin, LOW);
			delay(200); 
			 } */
		} 
  }
This is the info from the terminal
Starting NF-Reader...
Found chip PN532
Firmware ver. 1.6
NF-Reader started!
Waiting for an ISO14443A Card ...

Poll counter: 1
Success: 1
Found an ISO14443A card
UID Length: 4 bytes
UID Value: 0x03 0x11 0x5A 0xC2

UID_final: 304
Seems to be a Mifare Classic card (4 byte UID)
Reading Block 4:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................

url: /PhpProjectThesis/add_data.php?id=304&im_type=1&sublo=4 HTTP/1.0
connecting...

RESULTS:
command_1: 0
command_2: 0

Next poll in 10

Poll counter: 2
Success: 1
Found an ISO14443A card
UID Length: 4 bytes
UID Value: 0xE3 0x71 0x67 0xC2

UID_final: 638
Seems to be a Mifare Classic card (4 byte UID)
Reading Block 4:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................

url: /PhpProjectThesis/add_data.php?id=638&im_type=1&sublo=4 HTTP/1.0
connecting...

RESULTS:
command_1: 0
command_2: 0

Next poll in 10

Poll counter: 3
Success: 1
Found an ISO14443A card
UID Length: 4 bytes
UID Value: 0xE3 0x71 0x67 0xC2

UID_final: 637
Seems to be a Mifare Classic card (4 byte UID)
Reading Block 4:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................

url: /PhpProjectThesis/add_data.php?id=637&im_type=1&sublo=4 HTTP/1.0
connecting...

RESULTS:
command_1: 0
command_2: 0

Next poll in 10

Poll counter: 4
Success: 1
Found an ISO14443A card
UID Length: 4 bytes
UID Value: 0xE3 0x71 0x67 0xC2

UID_final: 637
Seems to be a Mifare Classic card (4 byte UID)
Reading Block 4:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................

url: /PhpProjectThesis/add_data.php?id=637&im_type=1&sublo=4 HTTP/1.0
connecting...

RESULTS:
command_1: 0
command_2: 0

Next poll in 10

Poll counter: 5
Success: 1
Found an ISO14443A card
UID Length: 4 bytes
UID Value: 0xE3 0x71 0x67 0xC2

UID_final: 637
Seems to be a Mifare Classic card (4 byte UID)
Reading Block 4:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................

url: /PhpProjectThesis/add_data.php?id=637&im_type=1&sublo=4 HTTP/1.0
connecting...

RESULTS:
command_1: 0
command_2: 0

Next poll in 10

Poll counter: 6
Success: 1
Found an ISO14443A card
UID Length: 4 bytes
UID Value: 0xE3 0x71 0x67 0xC2

UID_final: 637
Seems to be a Mifare Classic card (4 byte UID)
Reading Block 4:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................

url: /PhpProjectThesis/add_data.php?id=637&im_type=1&sublo=4 HTTP/1.0
connecting...

RESULTS:
command_1: 0
command_2: 0

Next poll in 10

Poll counter: 7
Success: 1
Found an ISO14443A card
UID Length: 4 bytes
UID Value: 0x03 0x11 0x5A 0xC2

UID_final: 325
Seems to be a Mifare Classic card (4 byte UID)
Reading Block 4:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................

url: /PhpProjectThesis/add_data.php?id=325&im_type=1&sublo=4 HTTP/1.0
connecting...

RESULTS:
command_1: 0
command_2: 0

Next poll in 10

Poll counter: 8

PD: i am using Arduino IDE 1.0.2. With a newer version it doesnt connect

User avatar
adafruit_support_rick
 
Posts: 35092
Joined: Tue Mar 15, 2011 11:42 am

Re: NFC Shield inconsistency with reading tags

Post by adafruit_support_rick »

Code: Select all

       for (int i = 0; i < 8; i++) {          //iterate over array, take value and write to ID_final as an integer
         id = id + uid[i];
       }
Looks to me like you're summing 8 bytes of either a 4-byte or 7-byte buffer. So you're going to be adding in garbage from beyond the end of the buffer.

User avatar
Maiu_bm
 
Posts: 5
Joined: Thu Aug 14, 2014 5:20 am

Re: NFC Shield inconsistency with reading tags

Post by Maiu_bm »

Hey, i made a new change on the signaled part based on the Babel Fish project

Code: Select all

 if (success) {
    // Found a card!
    
 
        Serial.print("Card detected #");
        // turn the four byte UID of a mifare classic into a single variable #
        id = uid[3];
        id <<= 8; id |= uid[2];
        id <<= 8; id |= uid[1];
        id <<= 8; id |= uid[0];
        Serial.println(id);
       }  
Right now, it reads all the tags that i have and it is a constant value until now. My doubt is that i have a new rfid MiFare Clear Tag #361. and the value obtained is negative. I though that the values where always positive, maybe i am wrong. What do you think about it?

Code: Select all

Poll counter: 6
Success: 1
Card detected #-10700
Found an ISO14443A card
  UID Length: 4 bytes
  UID Value: 0x34 0xD6 0x41 0xF4

UID_final: -10700
Seems to be a Mifare Classic card (4 byte UID)
Reading Block 4:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................

url: /ArduinoPHP/add_data.php?id=-10700&im_type=1&sublo=4 HTTP/1.0
connecting...

Info from the serial monitor

User avatar
adafruit_support_rick
 
Posts: 35092
Joined: Tue Mar 15, 2011 11:42 am

Re: NFC Shield inconsistency with reading tags

Post by adafruit_support_rick »

You're shifting 32 bits into a 16-bit integer. You want to declare id as type long to make it 32 bits. If you need it to be unsigned, declare it as unsigned long id;

Currently, id is a signed 16-bit integer. The way you're shifting in the data, you will wind up with 0xD634 in id, which is -10700 decimal. If you make it a signed long, you will still get a negative number, since you will have 0xF441D634, which is -197011916 decimal. If you make it unsigned long, you will wind up with a value of 4097955380 decimal

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino Shields from Adafruit”