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);
}
}
The vast majority of what's going on here is happening inside the MFRC522
class, which we can't see because it's included from some header file. For an explanation of that you should probably go to the documentation of wherever you got MFRC522.h
However you specifically asked about the ternary, seen here:
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);
}
}
Here we're looping through an array of bytes and printing them out in hexadecimal.
Presumably Serial.print(n, HEX)
prints a number in hexadecimal. The problem with this, apparently, is that we want our output to look like, say,
FF 03 FF FF 00
whereas if we just printed out each byte in hexadecimal we'd get
FF 3 FF FF 0
So the code here is working around this by checking if the number is only going to be one digit long (that is, less than 0x10), and, if so, printing out a zero before it prints out the number:
Serial.print(buffer[i] < 0x10 ? " 0" : " "); //Ternary returns 0 if < 0x10