You are currently viewing 用Arduino建立夜間安全燈

用Arduino建立夜間安全燈

在這個項目中,您將使用繼電器模組、光敏電阻和Arduino建立夜間安全燈。

夜間安全燈僅在天黑且檢測到物體移動時才會打開。

這是該項目的主要功能:

  • 漆黑時燈亮並且檢測到物體運動。
  • 當檢測到運動時,指示燈將保持點亮狀態10秒鐘。
  • 當指示燈點亮並檢測到運動時,它將再次開始計數10秒鐘。
  • 當有光時,即使檢測到運動,燈也會關閉。

推薦資源

所需零件

  • Arduino UNO 
  • PIR物體移動感測器 
  • 光敏電阻 
  • 10kOhm電阻
  • 繼電器模組 
  • 燈線組
  • 麵包板 
  • 跳線 

程式碼

警告:當您的燈泡連接到電源電壓時,請勿將程式碼上傳到Arduino板上。在將新的草稿碼上傳到Arduino之前,您應該從主電源上拔下燈泡的電源。

/*
 * Terry Lee 
 * 完整程式碼說明,請參閱 http://randomnerdtutorials.com
 */
 
// 繼電器引腳用D8控制。電源線連接到常閉和共同
int relay = 8;
volatile byte relayState = LOW;

// PIR運動感測器連接到D2
int PIRInterrupt = 2;

// 光敏電阻引腳連接到A0
int LDRPin = A0;
// 光敏電阻值會存在LDRReading變數
int LDRReading;
// 光敏電阻臨界值
int LDRThreshold = 300;

// Timer Variables
long lastDebounceTime = 0;  
long debounceDelay = 10000;

void setup() {
  // Pin for relay module set as output
  pinMode(relay, OUTPUT);
  digitalWrite(relay, HIGH);
  // PIR motion sensor set as an input
  pinMode(PIRInterrupt, INPUT);
  // Triggers detectMotion function on rising mode to turn the relay on, if the condition is met
  attachInterrupt(digitalPinToInterrupt(PIRInterrupt), detectMotion, RISING);
  // Serial communication for debugging purposes
  Serial.begin(9600);
}

void loop() {
  // If 10 seconds have passed, the relay is turned off
  if((millis() - lastDebounceTime) > debounceDelay && relayState == HIGH){
    digitalWrite(relay, HIGH);
    relayState = LOW;
    Serial.println("OFF");
  }
  delay(50);
}

void detectMotion() {
  Serial.println("Motion");
  LDRReading = analogRead(LDRPin);
  // LDR Reading value is printed on serial monitor, useful to get your LDRThreshold
  //Serial.println(LDRReading);
  // Only turns the Relay on if the LDR reading is higher than the LDRThreshold
  if(LDRReading > LDRThreshold){
    if(relayState == LOW){
      digitalWrite(relay, LOW);
    }
    relayState = HIGH;  
    Serial.println("ON");
    lastDebounceTime = millis();
  }
}

原理圖

安全警告!

當您製作連接到電源電壓的項目時,你真的需要知道你在做什麼,否則你可能會讓自己受傷。
這是一個嚴肅的話題,我希望你能夠安全。如果你不是100%確定你在做什麼,幫自己一個忙,不要碰任何事情。
問知道的人!

這是該項目的示意圖。

注意:如果您在電源電壓電纜(黃色和綠色電纜)中具有接地(GND)連接,則該電纜應位於繼電器模組的外部,如藍色導線(中性線)。

範例

總結

在此項目中,您建立了帶有光敏電阻和PIR物體移動感測器的夜間安全燈。

這是一個與繼電器和PIR運動傳感器一起練習的好項目。

如果您喜歡Arduino項目,請確保檢查我們最新的Arduino課程。

謝謝閱讀!

發佈留言