arduino IC卡读写的代码
时间: 2023-05-29 10:01:28 浏览: 122
arduino代码
以下是一个简单的Arduino IC卡读写代码示例,可用于Mifare卡(如Mifare Classic或Mifare Ultralight):
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);
void setup() {
Serial.begin(9600);
SPI.begin();
mfrc522.PCD_Init();
Serial.println("Scan IC card to see UID and type...");
}
void loop() {
// Look for new cards
if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
// Print card UID and type
Serial.print("UID: ");
for (byte i = 0; i < mfrc522.uid.size; i++) {
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
}
Serial.print(" Type: ");
mfrc522.PICC_Type(mfrc522.PICC_GetType(mfrc522.uid.sak));
// Try to write to card (for Mifare Classic)
if (mfrc522.PICC_GetType(mfrc522.uid.sak) == MFRC522::PICC_TYPE_MIFARE_1K) {
MFRC522::MIFARE_Key key;
byte sector = 1;
byte block = 4;
// Set key
for (byte i = 0; i < 6; i++) {
key.keyByte[i] = 0xFF;
}
// Authenticate sector
if (mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, sector, &key, &(mfrc522.uid)) == MFRC522::STATUS_OK) {
// Write to block
byte buffer[18] = "Hello, world!";
if (mfrc522.MIFARE_Write(block, buffer, 16) == MFRC522::STATUS_OK) {
Serial.println("Successfully written to block 4.");
}
}
}
// Halt PICC
mfrc522.PICC_HaltA();
mfrc522.PCD_StopCrypto1();
}
}
阅读全文