I never could get this to work with the Particle Boron using the code I’ve found in this thread. I think it’s because calling delay()
does magic things on Particle GEN3 devices, and breaks things. Anyway, here’s my current code that resets the RFID reader after each tag scan and every 5 seconds, whichever comes first. That’s a bit aggressive, but it’s helping with reliability.
// This #include statement was automatically added by the Particle IDE.
#include <MFRC522.h>
#define LED_PIN D7
#define TONE_GND D5
#define TONE_PIN D4
// Define the serial data and reset pins.
#define SS_PIN SS
#define RST_PIN D8
// NFC card reader init
MFRC522 mfrc522(SS_PIN, RST_PIN);
// Keep track of the last time we recorded the time
uint32_t lastMillis = 0;
void setup() {
pinMode(TONE_GND, OUTPUT);
pinMode(TONE_PIN, OUTPUT);
digitalWrite(TONE_GND, LOW);
digitalWrite(TONE_PIN, LOW);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
Particle.publish("status", "boot", 60, PRIVATE, WITH_ACK);
}
void initRC522() {
SPI.begin(); // Init SPI bus
SPI.setClockDivider(SPI_CLOCK_DIV16);
mfrc522.PCD_Init(); // Init MFRC522
delay(50);
digitalWrite(LED_PIN, HIGH);
}
void killRC522() {
digitalWrite(RST_PIN, LOW);
digitalWrite(LED_PIN, LOW);
}
void beep() {
tone(TONE_PIN, 1500, 400);
delay(500);
tone(TONE_PIN, 2000, 400);
delay(500);
}
void blink() {
RGB.color(0, 255, 255);
delay(90);
RGB.color(0, 0, 0);
delay(90);
RGB.color(5, 5, 5);
}
void loop() {
RGB.control(true); // take control of onboard RGB led
// Indicate we're in our card reading loop
RGB.color(3, 3, 3);
// Initialize RFID reader
initRC522();
// Reset last ms timer
lastMillis = millis();
// Wait up to N ms for card reading
while (millis() - lastMillis < 5000) {
// Look for a new NFC card to be present
if (!mfrc522.PICC_IsNewCardPresent()) {
continue;
}
// Attempt to read the card serial number (uid)
if (!mfrc522.PICC_ReadCardSerial()) {
continue;
}
// Card was read
char cardID[32] = "";
for (byte i = 0; i < mfrc522.uid.size; i++) {
char hex[4];
snprintf(hex, sizeof(hex), "%02x", mfrc522.uid.uidByte[i]);
strncat(cardID, hex, sizeof(cardID));
}
// tell the card to go to sleep
mfrc522.PICC_HaltA();
// Green indicator for card read
RGB.color(0, 255, 0);
Particle.publish("tag", cardID, 60, PRIVATE, WITH_ACK);
beep();
break;
}
killRC522();
blink();
}