I kindly need your help with the project I am working on. The project is supposed to activate the relay for 5 seconds using a predefined rfid card. The card value is 1000000 and for every use/ relay activation the figure is reduced by 500. I am supposed to get a visual feedback using the serial monitor but the code is failing to give results.
The code is below:
#include <MFRC522.h>
#include <SPI.h>
#define RST_PIN 0 // RST Pin connected to GPIO 0
#define SS_PIN 2 // SS Pin connected to GPIO 2
#define RELAY_PIN 12 // Relay Pin connected to GPIO 12
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
unsigned long initialBalance = 1000000; // Initial balance
unsigned long remainingBalance = initialBalance; // Remaining balance
unsigned long cardUsageTimeout = 0; // Timeout for card usage relay activation
const unsigned long relayActivationTime = 5000; // Relay activation time in milliseconds
void setup() {
Serial.begin(9600); // Initialize Serial Monitor
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
pinMode(RELAY_PIN, OUTPUT); // Set relay pin as output
digitalWrite(RELAY_PIN, LOW); // Set relay initial state as low
Serial.println("Scan your RFID card to deduct $500.");
Serial.print("Initial Balance: $");
Serial.println(initialBalance);
}
void loop() {
// Look for new cards
if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
String cardID = String(mfrc522.uid.uidByte[0], HEX) +
String(mfrc522.uid.uidByte[1], HEX) +
String(mfrc522.uid.uidByte[2], HEX) +
String(mfrc522.uid.uidByte[3], HEX);
if (cardID.equals("bac47b3")) {
// Check if the relay activation timeout has passed
if (millis() >= cardUsageTimeout) {
// Deduct $500 from the balance
remainingBalance -= 500;
// Activate the relay for 5 seconds
digitalWrite(RELAY_PIN, HIGH);
delay(relayActivationTime);
digitalWrite(RELAY_PIN, LOW);
// Update the card usage timeout
cardUsageTimeout = millis() + relayActivationTime;
// Display initial and remaining balance
Serial.print("Initial Balance: $");
Serial.println(initialBalance);
Serial.print("Remaining Balance: $");
Serial.println(remainingBalance);
} else {
Serial.println("Relay is still active. Please wait before using the card again.");
}
} else {
Serial.println("Unauthorized card detected.");
}
// Halt PICC
mfrc522.PICC_HaltA();
}
}