Skip to content

Instantly share code, notes, and snippets.

@samsullivan
Created December 9, 2014 16:20
Show Gist options
  • Save samsullivan/ef7c5dd36a10c86f4c08 to your computer and use it in GitHub Desktop.
Save samsullivan/ef7c5dd36a10c86f4c08 to your computer and use it in GitHub Desktop.
Wait for NFC tag and verify against a stored UID using libnfc
#include <stdlib.h>
#include <nfc/nfc.h>
const uint8_t UID[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
void
checkForTag(nfc_device *pnd, nfc_modulation nm)
{
nfc_target nt;
if(nfc_initiator_select_passive_target(pnd, nm, NULL, 0, &nt) > 0) {
int i;
uint8_t scannedUid[nt.nti.nai.szUidLen];
for(i = 0; i < (int) nt.nti.nai.szUidLen; i++) {
scannedUid[i] = nt.nti.nai.abtUid[i];
}
if(memcmp(scannedUid, UID, sizeof(UID)) == 0) {
printf("Valid tag found!\n");
} else {
printf("Invalid tag...\n");
}
}
checkForTag(pnd, nm);
}
int
main(int argc, const char *argv[])
{
nfc_device *pnd;
nfc_context *context;
// Initialize libnfc and set the nfc_context
nfc_init(&context);
if (context == NULL) {
printf("Unable to init libnfc (malloc)\n");
exit(EXIT_FAILURE);
}
// Open NFC device
pnd = nfc_open(context, NULL);
if (pnd == NULL) {
printf("ERROR: %s\n", "Unable to open NFC device.");
exit(EXIT_FAILURE);
}
// Set opened NFC device to initiator mode
if (nfc_initiator_init(pnd) < 0) {
nfc_perror(pnd, "nfc_initiator_init");
exit(EXIT_FAILURE);
}
// Poll for a ISO14443A (MIFARE) tag
const nfc_modulation nm = {
.nmt = NMT_ISO14443A,
.nbr = NBR_106,
};
checkForTag(pnd, nm);
// Close and release NFC device
nfc_close(pnd);
nfc_exit(context);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment