I was wondering if someone could help comment on each line and go through the process of this code I found online? I seem quite confused especially with the ternary operator used. I would like to use it for my project but I don't like to use code that I do not properly understand. This code prints out the UID of the RFID tag scanned into the serial monitor but I'm not sure about each function.
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class
MFRC522::MIFARE_Key key;
// Init array that will store new NUID
byte nuidPICC[4];
void setup() {
Serial.begin(9600);
SPI.begin(); // Init SPI bus
rfid.PCD_Init(); // Init MFRC522
for (byte i = 0; i < 6; i++) {
key.keyByte[i] = 0xFF;
}
}
void loop() {
// Look for new cards
if ( ! rfid.PICC_IsNewCardPresent())
return;
// Verify if the NUID has been readed
if ( ! rfid.PICC_ReadCardSerial())
return;
for (byte i = 0; i < 4; i++) {
nuidPICC[i] = rfid.uid.uidByte[i];
}
printHex(rfid.uid.uidByte, rfid.uid.size);
Serial.println();
rfid.PICC_HaltA();
rfid.PCD_StopCrypto1();
}
void printHex(byte *buffer, byte bufferSize) { //Loops as big as UID size
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " "); //Ternary returns 0 if < 0x10
Serial.print(buffer[i], HEX);
}
}