RFID 無線感應音樂盒

🔹MFRC522 腳位接線

SDA (SS)D10
SCKD13
MOSID11
MISOD12
RSTD9
3.3V3.3V
GNDGND

⚠️ 注意:MFRC522 只能接 3.3V,不要接 5V

🔹 蜂鳴器接線


正極 (+)       D8
負極 (–)GND


#include <SPI.h>

#include <MFRC522.h>


#define RST_PIN 9    // 重置腳位

#define SS_PIN 10    // SDA 腳位

#define BUZZER_PIN 8 // 蜂鳴器腳位


MFRC522 mfrc522(SS_PIN, RST_PIN);  // 建立 RFID 物件


// 授權卡片 UID

byte birthdayUID[4] = {224, 202, 33, 16};

byte twinkleUID[4]  = {99, 101, 39, 254};


// 生日快樂歌音符

int birthdayMelody[] = {

  262, 262, 294, 262, 349, 330,

  262, 262, 294, 262, 392, 349,

  262, 262, 523, 440, 349, 330, 294,

  466, 466, 440, 349, 392, 349

};

int birthdayDurations[] = {

  250, 250, 500, 500, 500, 1000,

  250, 250, 500, 500, 500, 1000,

  250, 250, 500, 500, 500, 500, 1000,

  250, 250, 500, 500, 500, 1000

};


// 小星星音符

int twinkleMelody[] = {

  262, 262, 392, 392, 440, 440, 392,

  349, 349, 330, 330, 294, 294, 262

};

int twinkleDurations[] = {

  500, 500, 500, 500, 500, 500, 1000,

  500, 500, 500, 500, 500, 500, 1000

};


void setup() {

  Serial.begin(9600);

  SPI.begin();

  mfrc522.PCD_Init();

  pinMode(BUZZER_PIN, OUTPUT);

  Serial.println("請將卡片靠近讀卡器...");

}


void loop() {

  if (!mfrc522.PICC_IsNewCardPresent()) return;

  if (!mfrc522.PICC_ReadCardSerial()) return;


  Serial.print("卡片 UID (10進位): ");

  for (byte i = 0; i < mfrc522.uid.size; i++) {

    Serial.print(mfrc522.uid.uidByte[i], DEC);

    Serial.print(" ");

  }

  Serial.println();


  if (compareUID(mfrc522.uid.uidByte, birthdayUID)) {

    Serial.println("授權卡片 → 播放生日快樂歌");

    playSong(birthdayMelody, birthdayDurations, sizeof(birthdayMelody)/sizeof(int));

  } else if (compareUID(mfrc522.uid.uidByte, twinkleUID)) {

    Serial.println("授權卡片 → 播放小星星");

    playSong(twinkleMelody, twinkleDurations, sizeof(twinkleMelody)/sizeof(int));

  } else {

    noTone(BUZZER_PIN);

    Serial.println("非授權卡片 → 不播放");

  }


  mfrc522.PICC_HaltA();

}


// 比對 UID

bool compareUID(byte *uid, byte *target) {

  for (byte i = 0; i < 4; i++) {

    if (uid[i] != target[i]) return false;

  }

  return true;

}


// 播放歌曲

void playSong(int melody[], int durations[], int length) {

  for (int i = 0; i < length; i++) {

    tone(BUZZER_PIN, melody[i], durations[i]);

    delay(durations[i] * 1.3);

  }

  noTone(BUZZER_PIN);

}


留言