Created
August 8, 2019 17:47
-
-
Save stigok/322e1ced78e8f52b0f466506083acaef to your computer and use it in GitHub Desktop.
Golang libnfc read a tag or card with ACR122 reader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Related blog post: | |
// https://blog.stigok.com/2019/08/06/golang-with-libnfc-bindings-and-a-acr122u-a9-tag-reader.html | |
package main | |
import ( | |
"fmt" | |
"log" | |
"github.com/fuzxxl/nfc/2.0/nfc" | |
) | |
var ( | |
m = nfc.Modulation{Type: nfc.ISO14443a, BaudRate: nfc.Nbr106} | |
devstr = "acr122_usb:001:012" // Use empty string to select first device | |
) | |
// Blocks until a target is detected and returns its UID. | |
// Only cares about the first target it sees. | |
func get_card (pnd *nfc.Device) ([10]byte, error) { | |
for { | |
targets, err := pnd.InitiatorListPassiveTargets(m) | |
if err != nil { | |
return [10]byte{}, fmt.Errorf("listing available nfc targets", err) | |
} | |
for _, t := range targets { | |
if card, ok := t.(*nfc.ISO14443aTarget); ok { | |
return card.UID, nil | |
} | |
} | |
} | |
} | |
func main() { | |
fmt.Println("using libnfc", nfc.Version()) | |
pnd, err := nfc.Open(devstr) | |
if err != nil { | |
log.Fatalf("could not open device: %v", err) | |
} | |
defer pnd.Close() | |
if err := pnd.InitiatorInit(); err != nil { | |
log.Fatalf("could not init initiator: %v", err) | |
} | |
fmt.Println("opened device", pnd, pnd.Connection()) | |
card_id, err := get_card(&pnd) | |
if err != nil { | |
fmt.Errorf("failed to get_card", err) | |
} | |
if card_id != [10]byte{} { | |
fmt.Printf("card found %#X\n", card_id) | |
} else { | |
fmt.Printf("no card found\n") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment