ส่วนใหญ่จะใช้เวลาในการตรวจสอบพินเอาต์พุตของเซ็นเซอร์ตรวจจับความเคลื่อนไหว เมื่อพินนั้นเป็น HIGH ก็จะเปิดใช้งานกล้อง ถ่ายภาพเดียว และบันทึกลงในการ์ด SD ด้วยชื่อไฟล์ที่มีการประทับเวลา ก่อนที่จะกลับไปตรวจสอบอีกครั้ง
เซ็นเซอร์ตรวจจับความเคลื่อนไหวทำอะไรบ้าง
เซ็นเซอร์ PIR ตรวจจับสัญญาณความร้อนอินฟราเรดของวัตถุที่เคลื่อนที่ผ่านขอบเขตการมองเห็น และรายงานเป็นสัญญาณดิจิทัลแบบง่าย ซึ่งเป็นเทคโนโลยีการตรวจจับเดียวกันกับที่อยู่เบื้องหลังไฟที่ทำงานด้วยการเคลื่อนไหวในครัวเรือนส่วนใหญ่
เซ็นเซอร์ตรวจจับความเคลื่อนไหวทำงานตลอดเวลาโดยไม่มีสิ่งใดเคลื่อนไหว โมดูล PIR ส่วนใหญ่มีตัวปรับความไวและการหน่วงเวลาในตัว ให้ลดความไวลงและปล่อยให้เซ็นเซอร์ปรับสภาพตัวเองเป็นเวลาหนึ่งนาทีหลังจากเปิดเครื่องก่อนทำการทดสอบ
#include <SPI.h>
#include <SD.h>
// --- Pin definitions ---
// PIR and SD pins: pick any GPIOs that Freenove's camera_pins.h for your exact
// board does NOT list as in use by the camera/PSRAM interface. The pins below
// are a common example pattern - confirm against your board's pin definition
// header before wiring.
#define PIR_PIN 13 // PIR OUT (digital input, HIGH on motion)
#define SD_CS_PIN 1 // SD card module chip select
// SD_CS_PIN uses the board's default hardware SPI bus (SCK/MOSI/MISO) via SD.begin()
bool motionActive = false;
void setup() {
Serial.begin(115200);
pinMode(PIR_PIN, INPUT);
if (!SD.begin(SD_CS_PIN)) {
Serial.println("SD card init failed - check wiring/CS pin");
} else {
Serial.println("SD card ready");
}
}
void logMotionEvent(unsigned long timestampMs) {
File logFile = SD.open("/motion_log.txt", FILE_APPEND);
if (logFile) {
logFile.print("Motion detected at t+");
logFile.print(timestampMs);
logFile.println("ms");
logFile.close();
Serial.println("Logged motion event to SD");
} else {
Serial.println("Failed to open log file on SD");
}
}
void loop() {
bool motionNow = digitalRead(PIR_PIN) == HIGH;
if (motionNow && !motionActive) {
motionActive = true;
Serial.println("Motion started");
logMotionEvent(millis());
// --- Camera integration point (pseudocode) ---
// This is where you'd call into the camera example's real capture flow.
// The official CameraWebServer example (and esp_camera.h it's built on)
// uses these real, genuine functions - wire this in once you've loaded
// that example and confirmed your board's camera_pins.h:
//
// camera_fb_t *fb = esp_camera_fb_get();
// if (fb) {
// File imgFile = SD.open("/capture.jpg", FILE_WRITE);
// if (imgFile) {
// imgFile.write(fb->buf, fb->len);
// imgFile.close();
// }
// esp_camera_fb_return(fb);
// }
//
// Don't copy pin numbers from anywhere else - camera_pins.h from your
// loaded example already has them correct for your board.
} else if (!motionNow && motionActive) {
motionActive = false;
Serial.println("Motion ended");
}
delay(200);
}