Social Icons

Simple NFC reading system for windows



I wanted to create an attendance capturing system with using NFC tags. This is what I have done. Hope somebody will take advantage from this.
I’ve used ACR122u as the NFC reader and Mifare Classic 1K cards as tags. Technically used C# language with WPF interfaces and winscard.dll which is contains functions to expose Personal Computer/Smart Card (PC/SC) services for using smart cards and smart card readers.



I’ve developed simple WPF application, contains two basic functions.
     1.Get UID of the NFC tag      2.Write and read data to the NFC tag
when the application starts, system will detect the connected NFC reader and will established the context with the reader.



Get card UID:
Chip contains a unique serial number for identification purposes, this is called UID. So we can identify tag from other tags.
First of all we have to create following class on our solution.

Card.cs
This is main window code behind,


When we press the button 1, system will connect to the card on the reader and start to get the card UID. Here is rest of main window code:


Thank you very much!
Please comment below if you have any questions or errors or anything :)
From next post, I'll guide you to write and read data to the card.
Enjoy!!
Irantha Jayasekara



94 comments:

  1. How can I write data to the card? can we retrieve them back?

    ReplyDelete
    Replies
    1. Hello there,
      Sorry for the delay. I have added new post about write and read data from the NFC tag. check this link:
      http://the--semicolon.blogspot.com/p/read-and-write-to-nfc-tag.html

      Delete
  2. help sir... I get this error


    Error 1 'Card': member names cannot be the same as their enclosing type

    ReplyDelete
    Replies
    1. Hi Keli,
      I dont have any experience regrading that kind of error message. can you inbox me what have you tried? I'll try my best to help you. :)

      Delete
  3. This is great article, it's nice to found it...

    Sir, there is something I need to know... I am new for this kind things, and I don't know how to start... I have a acr 122u, I don't know about the card which have to 1K or 4K, I know visual basic, and stuck which once must I learned...

    About your article, is there any basic that I can read and learn? Thank you, Sir...

    ReplyDelete
    Replies
    1. Sir, I've already start using visual studio...

      I rename window1.xaml.cs ==> mainwindow.xaml.cs and class1.cs ==> card.cs...
      I have and error : The type or namespace name 'DllImport' could not be found, something I miss to do? Thank you for your support...

      Delete
    2. Hello,

      I've already fix the error with "using System.Runtime.InteropServices;"...
      I'll try to click the first button, and pop-up show "Card not available"...

      Is there anything I can do?

      Thank you..

      Delete
    3. Hi Duni,
      Do you familiar with C#? This is a WPF simple application, which is looks similar to a windows form application.
      So what is your OS? windows 7 or 8?

      Delete
    4. What you want to do is, connect the reader to the USB port, LED will turn on.
      Run the application, place the card on the reader. press the button

      Delete
  4. Hi, thank you for your reply...

    I am not good in C#, have a little know about C++, I use window 8...
    I already connect the acs, then the red lamp turn on, I run the application, then the green lamp turn on, click the forst button, pop-up "card not available with ? in the message"...

    Thanks :D

    ReplyDelete
    Replies
    1. I forget, I put the card in the card reader, then the green lamp turn on, then I click the first button, the pop-up window message show-up...

      Regards...

      Delete
    2. Can you confirm the card type? you can use android or any other free application, will you?

      Delete
    3. Hi,

      My friend (he don't know the code too) give me the demo application. I'll run the application, then show me the card data :
      Successful connection to ACS ACR122 0
      << FF CA 00 00 00
      >> 9000
      >> 3F F4 26 00

      I don't know the card type... How can I know? From the first I bought?
      I am really sorry if I not smart enough and disturbing you...

      Delete
    4. Mr. Irantha Jayasekara,

      My pleasure if you accept the friend request from me via Facebook, thank you...

      Delete
    5. Hi,

      When I run the application, 1 warning in the error list box, show up :
      'CardReader.MainWindow.Close()' hides inherited member 'System.Window.Close()'. Use the new keyword if hiding was intended.

      Is there anything to do with this?
      Thank you

      Delete
    6. Thank you for the guide, success application...

      Delete
  5. Replies
    1. Hi Yilmaz,
      I don't understand your question.
      I worked on VS2010 with C#. Please describe your question :)

      Delete
    2. Hi Irantha
      I don't know english. I want to this application asp.net c# project please.

      Delete
  6. Hi Thanks for your great article.
    Just have a question.
    How to know the card is tagged?
    as like as delegate or callback.

    I want to show cardUID when the card is tagged onto reader.
    Thanks.

    ReplyDelete
    Replies
    1. Hi Ming,

      You have to catch the event, "changing card state" for that.
      hint : SCardGetStatusChange()

      Good luck

      Delete
    2. do you have any code this. or can you tell me the steps

      Delete
  7. Do you have a code for VB.NET language? i badly need to connect acr122u at our attendance system..

    ReplyDelete
  8. Thank you so much Mr Irantha your codes are very useful on our thesis development. These codes are the only one that helped a lot on our progress.I am new in this development its a bit confusing. in the given codes you store data on block that is = 5 is that the only block that i can store data? If there are others how do i know?

    ReplyDelete
    Replies
    1. Hi Carlos,

      No there are lot of blocks you can write data in to. but there are several blocks you should not write in to.
      Read this article for more : https://learn.adafruit.com/adafruit-pn532-rfid-nfc/mifare

      Delete
  9. I only want to retrieve data from NFC Mifare ultralight. But how to identify that which block contain the data? and also when I use Block No 5 in below code-

    retCode = Card.SCardTransmit(hCard, ref pioSendRequest, ref SendBuff[0],
    SendLen, ref pioSendRequest, ref RecvBuff[0], ref RecvLen);

    if (retCode != Card.SCARD_S_SUCCESS)
    {
    WriteLogFile("Fail_transmit_" + retCode.ToString() + "_" + DateTime.Now);
    return retCode;
    }

    else
    {
    try
    {
    tmpStr = "";
    switch (reqType)
    {
    case 0:
    for (indx = (RecvLen - 2); indx <= (RecvLen - 1); indx++)
    {
    tmpStr = tmpStr + " " + string.Format("{0:X2}", RecvBuff[indx]);
    }

    I get tmpStr= 63 00 . why i get this ? Can you please help me out .

    ReplyDelete
  10. Replies
    1. Sorry, I didn't try it with Windows Phone. You can try and let us know ;)

      Delete
    2. I am Trying This

      error on below line
      retCode = Card.SCardConnect(hContext, readername, Card.SCARD_SHARE_SHARED,
      Card.SCARD_PROTOCOL_T0 | Card.SCARD_PROTOCOL_T1, ref hCard, ref Protocol);


      An exception of type 'System.NotSupportedException' occurred in Unknown Module. but was not handled in user code

      Delete
  11. Carsten SchildknechtMay 21, 2015 at 2:07 AM

    Hey there,
    first of all grt article! Im kinda new to the RFID thing in C# and got an Issue with detecting my Reader - Im using the ACS ACR122u and the Mifare 1k - I got no error displayed but im not getting any information, seems like i cant even connect the card and get the UID.

    ReplyDelete
    Replies
    1. Carsten SchildknechtMay 21, 2015 at 2:17 AM

      Is there any possible way u could upload ur working project files?

      Delete
    2. Whole code is over there, you can send me what you have tried. i will check and let you know.

      Delete
  12. Hi, I'm a trying to build the project with your source code, to see if my reader can communicate with Mifare ultralight/desfire card, but I'm struggling with import. Where could I find winscard.dll? I know I'm asking basics, but project setup is always very hard for me...thank you for your answer.

    ReplyDelete
    Replies
    1. winscard.dll comes with your reader driver i guess

      Delete
  13. It's great, How can I download the whole project's source code?

    ReplyDelete
    Replies
    1. This is the whole code. you can create new project and use this code. let me know if you get stuck

      Delete
  14. Hi, I'm trying to build the projet but il has some erreurs. If it is possible, can you upload the whole project's source code or working project files?

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Hi Petr Toth,

      Now i am able to READ/WRITE on the particular block of card .But the still problem is that i have to WRITE DATA on all the blocks at once and same for READ DATA at once as well.

      So if i m doing it by looping method then "FailAuthentication" error is occurring in both the cases.

      Please suggest needful in order to WRITE AND READ DATA in all blocks at once.

      Delete
  16. Hi Sir ,
    How to format mifare card

    ReplyDelete
  17. Great!
    May i know, is the must to use ACR122u reader? if i use other reader, can it still work?

    ReplyDelete
    Replies
    1. Im sorry , I didn't check it with other readers.

      Delete
  18. cardUID = BitConverter.ToString(receivedUID.Take(4).ToArray()).Replace("-", string.Empty).ToLower();

    'Take' command get red line how to fix :(

    ReplyDelete
  19. Can you please zip this project and upload? I would like to download the project.

    ReplyDelete
    Replies
    1. This is the whole code. nothing more than that

      Delete
  20. hello sir how can i detect card without clicking the button i used timer but my application become unresponsive sometimes

    ReplyDelete
  21. There is no code listed here. This is all that is visible:

    Card.cs
    This is main window code behind,


    When we press the button 1, system will connect to the card on the reader and start to get the card UID. Here is rest of main window code:

    ReplyDelete
  22. I can not see the code in Card.cs in the post. Have you quit it ?
    I need it.. please Help me.

    ReplyDelete
    Replies
    1. your network is likely blocking the gethub links that list the code

      Delete
  23. Hey mr Jayasekara!
    This small piece of code works really great! Actually it's kind of amazing because I did in fact uninstall the driver that come with the reader. Okey, maybe the dll is still in windows folder etc. sp I gues I might be using the drivers without mu knowledge, but whatever..
    I have a small problem, the only thing I really need is to read the UID of the card. I have 5 different cards/tags but I only have the cardno written down on one card - and of course that is not what comes out from GetUID APDU. I guess this card is probably one of those 4k cards (mifare plus).
    So I guess I am in need of two things:
    anyone knows how to receive UID of a 4k card? In this example we ask the card for the bytes, 1. right? Or is it maybe the reader that converts our requests and reads the 4 first bytes of sector 0? Anyway, amatour´as I am I just read the first 7 bytes, but no luck, the result makes no sense.
    2. anyone knows how to make those bytes into human readble numbers? What I did, I did use that hex-string this example builds, and then I did go to an online hex2dec converter (for instance http://www.binaryhexconverter.com/hex-to-decimal-converter).
    But the numbers do not end up the same as those printed.
    and by a fact I know the printed numbers are the UID, this is validated by playing around with a printer with nfc reader, this printer read the numbers correct.

    again, awesome article! (no need to use a framework here)

    ReplyDelete
    Replies
    1. OK, never mind, found out what was wrong. had to swap the hex bytes

      Delete
    2. Sorry mate, I couldn't come here lately. Im glad you make it. Cheers !

      Delete
  24. Dear Irantha Jayasekara,
    I cannot detect UID with the code that you provided. Please take your spare time to look at my code at https://www.dropbox.com/s/bh8l9jairdyvjw4/NFCTagData.rar?dl=0
    I will really appreciate for your help.

    ReplyDelete
    Replies
    1. What did it return with "connectCard()" function?

      Delete
    2. It returned a message box with the "?" sign.

      Delete
    3. Did you place the NFC tag on the NFC reader while running the code? It was returning "?" sign to me until i placed the tag.

      Delete
    4. Yes, I replaced the NFC tag on the reader, but returned the same error.

      Delete
  25. Hi i have a question how can i integrate the new nfc acr1252u to the sample program above? Please help
    Thanks

    ReplyDelete
  26. How can we set the buzzer off and on?
    I have tried this for acr1252u but it gives me 1!
    public void turnOffBuzzer()
    {
    retCode = Card.SCardConnect(hContext, readername, Card.SCARD_SHARE_SHARED, Card.SCARD_PROTOCOL_T0 | Card.SCARD_PROTOCOL_T1, ref hCard, ref Protocol);
    byte data= 0x00 ;
    byte[] control = new byte[] { 0xE0, 0x00, 0x00, 0x28, 0x01 };
    uint value = BitConverter.ToUInt32(control, 0);
    byte receivedBytes = new byte();
    int pcbBytesReturned = 0;
    long status = Card.SCardControl(hCard, value, ref data, 1,ref receivedBytes , 1, ref pcbBytesReturned);
    MessageBox.Show(status.ToString());
    }

    ReplyDelete
    Replies
    1. Hi Farzad Moghaddampoor how do you connect the acr1252u on the winscard? Can you give me a codes thanks

      Delete
    2. well first you need to find the hcontext by writing the code like this:
      public void SelectDevice()
      {
      List availableReaders = this.ListReaders();
      this.RdrState = new Card.SCARD_READERSTATE();
      readername = availableReaders[0].ToString();//selecting first device
      this.RdrState.RdrName = readername;
      foreach (string obj in availableReaders)
      {
      lstReaders.Items.Add(obj);
      }
      }
      internal void establishContext()
      {
      retCode = Card.SCardEstablishContext(Card.SCARD_SCOPE_SYSTEM, 0, 0, ref hContext);
      if (retCode != Card.SCARD_S_SUCCESS)
      {
      MessageBox.Show("Check your device and please restart again", "Reader not connected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
      connActive = false;
      return;
      }
      }

      Delete
  27. Hi Farzad Moghaddampoor how do you connect the acr1252u on the winscard? Can you give me a codes thanks

    ReplyDelete
  28. How i can get the UID automatically without click button 1 ??

    ReplyDelete
  29. If somebody could paste code for x64 that would be great.
    This example works perfect bu requires x86 system.

    Thanks

    ReplyDelete
  30. Nice One!!!! But can you tell me how to integrate this code with qt creator

    ReplyDelete
  31. Hello Sir,

    First of all THANK YOU for making your coding available so that beginners like us can get our heads around the technology.

    If there is nothing displayed on screen when card is put on reader is it normal because nothing has been put in it? Also, if I have built an application using VB.net how can I run the application once the card has been in contact with the reader?

    ReplyDelete
    Replies
    1. Hello Sir, never mind I got it to work thanks again for your amazing work!

      Delete
  32. Dear Sir,

    I am trying the above example with HID OMNIKEY5421, The reader is showing perfectly, but when i press connect its give a question mark error. I present the Card as well, but the result same with a question mark
    My system x64,

    Thanks in Advance

    ReplyDelete
    Replies
    1. Hi Abhilash,

      check whether you get your reader on from "SelectDevice()" function. I didnt check with OMNIKEY devices.

      Delete
    2. Hi Irantha,

      how do you connect the acr1252u on the winscard? Can you give me a codes thanks

      Delete
    3. Hi sir, i am trying the above example code the error is Inconsistent accessibility: field type 'nfc.Card.SCARD_READERSTATE' is less accessible than field 'nfc.MainWindow.RdrState' how can i fix it. tnx

      Delete
  33. Hi sir, i am trying the above example code the error is Inconsistent accessibility: field type 'nfc.Card.SCARD_READERSTATE' is less accessible than field 'nfc.MainWindow.RdrState' how can i fix it. tnx

    ReplyDelete
  34. Hi sir, how can i auto detect UID without clicking the button. Can you help me please. Tnx.

    ReplyDelete
  35. am convert this application into complete c# web based it works fine when i run it from visual studio. if hosted on iis the same code is not working it showing "Check your device and please restart again Reader not connected" can you please tell me the problem

    ReplyDelete
  36. Hi Sir

    Will this code work with ACS ACR 1251U

    ReplyDelete
  37. Hi,
    I get this error
    "Unable to find an entry point named 'SCardConnect' in DLL 'winscard.dll'."
    can you help me? thanks

    ReplyDelete
  38. Hi,some of old cards are not reading ,but when i write that card freshly it's reading please give me any suggestion for this?

    ReplyDelete
  39. Dear Irantha Jayasekara,

    This is very cool example for the same class application. I'm trying write application using also this code. I write smart card reader application and I would like to ask you for advice

    ReplyDelete
  40. can you please provide the code in VB

    ReplyDelete
  41. First, thank you for your code samples!

    I have used your code sample to successfully connect to the NFC reader and get status. However, when I attempt to read an NFC tag, I get the "FailedAuthentication" error.

    In the authenticateBlock method, SendAPDUandDisplay(0) returns a value of 6 instead of 0.

    I would like to know how to read all info from the tag if possible.

    Thanks

    My setup is as follows:
    Reader: ACR122U-A9
    Tag: NXP MIFARE Ultralight (NTAG213)
    Data Format: NFC Forum Type 2
    Record 0: UTF8 - plain text

    ReplyDelete
  42. Help new in cs..
    How do i do it in vs to run then code..I try new project, but it look like i dont get the form, and many errors

    ReplyDelete
  43. Hello Sir! Thanks for the great article.
    I am struggling with some issue here. I need to control the reader itself, ACR1252U, e.g. make the buzzer sound. I am using a pcsc-csharp library and use the control method which requires ControlCode 3500. Please help me understand how I can send this control code.
    Thanks.

    ReplyDelete
  44. This comment has been removed by the author.

    ReplyDelete
  45. Hello sir, can i get the project of the whole attendance system in zip code?

    ReplyDelete
  46. Can you pls provide code for mifare 4k and ultralight cards? also provide how to check card type?

    ReplyDelete
  47. hi irantha, i have error on reader not connected even i attached the reader. tried solve the problem but still it appear.

    ReplyDelete
  48. How can i use it to read another tag?

    ReplyDelete