I'm creating a simple RFID card reader using RC522 & sending the card UID with Bluetooth to my android app.
Sometimes it works and sometimes it doesn't pass the testing of PICC_IsNewCardPresent when I restart the power.
I have added the esp32 led on of to see if it pass this if block:
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
digitalWrite(LED_BUILTIN, HIGH);
delay(200);
digitalWrite(LED_BUILTIN, LOW);
Sometimes, when it works the led blinks, but sometimes when I switch the power off and then back on, it doesn't pass.
When I put the led blinking inside this if block it is blinking:
if ( ! mfrc522.PICC_IsNewCardPresent()) {
digitalWrite(LED_BUILTIN, HIGH);
delay(200);
digitalWrite(LED_BUILTIN, LOW);
return;
}
So I'm not sure if my code is wrong, or is there something else?
Here is the full code:
#include <SPI.h>
#include <MFRC522.h>
#include "BluetoothSerial.h"
#define SS_PIN 5
#define RST_PIN 22
MFRC522 mfrc522(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key;
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
BluetoothSerial SerialBT;
void setup() {
Serial.begin(115200);
SPI.begin(); // Initiate SPI bus
mfrc522.PCD_Init(); // Initiate MFRC522
for (byte i = 0; i < 6; i++) {
key.keyByte[i] = 0xFF;
}
SerialBT.begin("RFID Card Reader");
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
// just to test if it goes here (blink blue led on esp32)
digitalWrite(LED_BUILTIN, HIGH);
delay(200);
digitalWrite(LED_BUILTIN, LOW);
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}
char str[32] = "";
array_to_string(mfrc522.uid.uidByte, 4, str);
Serial.println(str);
SerialBT.print(str);
SerialBT.println();
delay(1000);
mfrc522.PICC_HaltA();
mfrc522.PCD_StopCrypto1();
}
void array_to_string(byte array[], unsigned int len, char buffer[])
{
for (unsigned int i = 0; i < len; i++)
{
if (i == 0)
sprintf(buffer, "%02X", array[i]);
else
sprintf(&buffer[i*3-1], ":%02X", array[i]);
}
}