Social Icons

Pages

Simple NFC reading system for windows

Content upgraded and moved to my own website. Access here:
https://www.iranthajayasekara.com/blog/nfc-card-reading-system-with-acr122u-reader.html



113 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. 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. :)

    ReplyDelete
  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. Thanks for the link Mr Irantha.

    ReplyDelete
  10. 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
  11. Can use this code windows phone 8

    ReplyDelete
    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
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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
  17. Hi Sir ,
    How to format mifare card

    ReplyDelete
  18. 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
  19. cardUID = BitConverter.ToString(receivedUID.Take(4).ToArray()).Replace("-", string.Empty).ToLower();

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

    ReplyDelete
  20. 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
  21. hello sir how can i detect card without clicking the button i used timer but my application become unresponsive sometimes

    ReplyDelete
  22. 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
  23. 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. I didn't remove it, it is there

      Delete
    2. your network is likely blocking the gethub links that list the code

      Delete
  24. 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
  25. 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
  26. Hi i have a question how can i integrate the new nfc acr1252u to the sample program above? Please help
    Thanks

    ReplyDelete
  27. 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
  28. Hi Farzad Moghaddampoor how do you connect the acr1252u on the winscard? Can you give me a codes thanks

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

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

    Thanks

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

    ReplyDelete
  32. 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
  33. 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
  34. 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
  35. Hi sir, how can i auto detect UID without clicking the button. Can you help me please. Tnx.

    ReplyDelete
  36. 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
  37. Hi Sir

    Will this code work with ACS ACR 1251U

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

    ReplyDelete
  39. 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
  40. 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
  41. can you please provide the code in VB

    ReplyDelete
  42. 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
  43. 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
  44. 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
  45. This comment has been removed by the author.

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

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

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

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

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

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

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

    ReplyDelete
  53. Hello Sir,

    I want to know which event occur when i punch the card with the reader, As my requirement is read the card automatically and register the card data in my database when the card is in range of reader. Kindly provide me the details.

    ReplyDelete
  54. string tmpStr = string.Empty;

    //Convert each byte from buff to its string value.
    for (int i = 0; i < buffLen; i++)
    tmpStr += string.Format("{0:X2}", buff[i]) + " ";

    //Add item to log (listBox)
    lstLog.Items.Add(prefixStr + tmpStr + postfixStr);

    //Select the last item from the listbox.
    lstLog.SelectedIndex = lstLog.Items.Count - 1;

    An unhandled exception of type 'System.IndexOutOfRangeException' occurred in ACR122RWIDValue.exe

    ReplyDelete
  55. Hello?...
    I am new to the readers, I have implemented the code and when connecting I get an error: "The specified reader name is not recognized.", What can it be?

    ReplyDelete
  56. i am trying to give reference of WinSCard.dll but it gives me version error (filoe could not be added), i could not find latest version of WinSCard.dll can any one provide me link of this dll.

    ReplyDelete
  57. Hy my name is georgian and i have a no name no brand nfc reader but i cant use can one of you make the aplication becouse i have no clue about c

    ReplyDelete
  58. thanks for the information .

    but may i ask question ?

    i dont want to use the button instead when the card tap if will trigger the function

    ReplyDelete
  59. Dear Sir . Would you please share entire project as folder with us ? I am new to WPF and having some troubles to make it run. Last comment is long time ago but still i want to try to reach you. I will be glad if you can help me. Regards

    ReplyDelete
  60. Hi Sir, I will encounter the error (The specific reader name is not recognized.' but I check the model of my device is same in your sample program.? Thanks and regards.

    ReplyDelete
  61. The NFC reader is not displayed in the readers list . ACR1281U . That is why i couldn't test it . Do anyone knows how to solve this problem ?

    ReplyDelete
  62. it says Card not avaialble: error "?" why is that happen??

    ReplyDelete
  63. Hi sir
    I want to get uid automatically when i scar tag with the reader. How to acheive it?Pl help

    ReplyDelete
  64. code does not run on a 64bit OS, please advise solution.
    please reply on rajan_singh@hotmail.com

    ReplyDelete
  65. Hey anyone help me plss.. I am new to C# wpf kindly guide me how to implement this code. i created this form design.. i am confused where i need to paste these codes actually ie; the card.cs and mainwindow.xaml.cs etc.. whether we nee to paste it on button 1 click kindly help me guys

    ReplyDelete
  66. Топ легальных азартных клубов поддерживает бренды, где можно выступать на деньги. Площадки имеют похвастаться резвыми выплатами сайты онлайн казино. Большинство требуют прохождение верификации. Среди игорных ресурсов возможно найти свежие порталы с минимальным депозитом от 1 $. Отличный отдых от заморочек за минимальную необходимую сумму — собственно может быть лучше?

    ReplyDelete
  67. Проверенные казино онлайн содержат круглосуточный саппорт. Клубы поддерживают минимум 3 способа связи — e-mail, онлайн-чат, жаркую линию. Некоторые энергично развивают каналы, группы в знаменитых социальных сетях. Клиенты могут задавать вопросы, обращаться с неуввязками. Операторы техподдержки консультируют и подскажут наилучшие игры рейтинг игровые автоматы, пояснят управляла, помогут с выводом выигрышей.

    ReplyDelete