/******************************
Author: Hay Chhuy
AM312 Sensor Code
Version: 1.0
Date: 29/08/2024
Last Update: Initial Version
******************************/
const int sensorLedPin = 12; // Indicates sensor state ON: motion detected, OFF: motion stopped
const int triggerPin = 2; // Pin connected to the AM312 PIR sensor
const int latchPin = 3; // Pin to be latched HIGH for 5 seconds
const int sensorPowerPin = 4; // Pin to control the power to the sensor (optional)
bool latchState = false; // Tracks if the latch is active
unsigned long latchStartTime = 0; // Records the time when latch started
unsigned long latchDuration = 5000; // Duration for which the pin should stay HIGH (5 sec)
void setup() {
pinMode(sensorLedPin, OUTPUT); // ON: motion detected, OFF: motion stopped
/***** for simulation where we enforce the AM312 sensor pin2 to HIGH
to do it, we need to alter the pin2 as OUTPUT not INPUT! ***********/
//pinMode(triggerPin, INPUT);
pinMode(latchPin, OUTPUT); // **** to be commented out when release
pinMode(triggerPin, OUTPUT); // **** to be commented out when release
pinMode(sensorPowerPin, OUTPUT); // Control pin for the sensor
digitalWrite(latchPin, LOW); // Initialize the latch pin to LOW
digitalWrite(sensorPowerPin, HIGH); // Ensure the sensor is powered on initially
Serial.begin(9600);
}
void loop() {
digitalWrite(triggerPin,HIGH);
// Check the sensor input (only if latch is not active)
if (!latchState) {
if (digitalRead(triggerPin) == HIGH) {
digitalWrite(sensorLedPin, HIGH);
Serial.println("Motion detected!");
latchState = true; // Activate latch state
latchStartTime = millis(); // Record the time latch started
digitalWrite(latchPin, HIGH); // Set the latch pin HIGH
digitalWrite(sensorPowerPin, LOW); // Disable the sensor (optional)
delay(1000); // Allow the sensor to power down
} else {
digitalWrite(sensorLedPin, LOW);
// Uncomment the next line if you want to see "Motion stopped!" when no motion is detected
Serial.println("Motion stopped!");
}
}
//Check if the latch is active and if the duration has passed
if (latchState && (millis() - latchStartTime >= latchDuration)) {
latchState = false; // Deactivate latch state
digitalWrite(latchPin, LOW); // Set the latch pin LOW after 5 sec
digitalWrite(sensorPowerPin, HIGH); // Re-enable the sensor (optional)
Serial.println("Motion stopped after latch time.");
}
}