---
# System prepended metadata

title: 學校超音波及近場感應

---

# 學校超音波及近場感應


```
include <Servo.h>

#define trigPin 3
#define echoPin 2
#define servoPin 5
#include <SPI.h>
#include <Wire.h>
#include <MFRC522.h>

#define RST_PIN         9          
#define SS_PIN          10 /

MFRC522 mfrc522;   

char *reference;

byte uid[]={0x0E, 0xB7, 0xED, 0xAE};  
int pass=0;



Servo myservo;

void setup() {
  Serial.begin(9600);
  myservo.attach(servoPin);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  SPI.begin();
  
  mfrc522.PCD_Init(SS_PIN, RST_PIN); // 初始化MFRC522卡
  Serial.print(F("Reader "));
  Serial.print(F(": "));
  mfrc522.PCD_DumpVersionToSerial(); // 顯示讀卡設備的版本
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration / 58.2;
  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
      // 顯示卡片的UID
      Serial.print(F("Card UID:"));
      dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size); // 顯示卡片的UID
      Serial.println();
      Serial.print(F("PICC type: "));
      MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
      Serial.println(mfrc522.PICC_GetTypeName(piccType));  //顯示卡片的類型
      
      //把取得的UID，拿來比對我們指定好的UID
      bool they_match = true; // 初始值是假設為真 
      for ( int i = 0; i < 4; i++ ) { // 卡片UID為4段，分別做比對
        if ( uid[i] != mfrc522.uid.uidByte[i] ) { 
          they_match = false; // 如果任何一個比對不正確，they_match就為false，然後就結束比對
          break; 
        }
      }
      
      //在監控視窗中顯示比對的結果
      if(they_match){
        Serial.print(F("Access Granted!"));
        pass==0;
      }else{
        Serial.print(F("Access Denied!"));
        pass==1;
      }
      mfrc522.PICC_HaltA();  // 卡片進入停止模式
    }

  if (distance <= 100&&pass==0) {
    myservo.write(120);  // micro servo 9G 轉動到 90 度的位置
    delay(1000);
  } else {3
    myservo.write(0);   // micro servo 9G 轉動到 0 度的位置
  }

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  delay(500);
}
//Card UID: 0E B7 ED AE
```
