/*
AM312 IR sensor with latching to hold the motion detected a bit longer(5000 0r 5 sec).
Simulation is included but for demonstration only and should be removed that part for real world.
*/
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)
// for simulation only ------------
unsigned long startSimulation = 0;
unsigned long endSimulation = 5500;
// ------------------------------
void setup() {
pinMode(sensorLedPin, OUTPUT); // ON: motion detected, OFF: motion stopped
pinMode(latchPin, OUTPUT);
pinMode(triggerPin, INPUT);
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);
// for simulation only ----
startSimulation = millis();
//-------------------------
}
void loop() {
// WOKWi Simulation ONLY ---------------------------------------------------
if (millis() - startSimulation >= endSimulation){
digitalWrite(triggerPin, HIGH); // Simulate sensor trigger
activateSensor();
// Reset the simulation timer after activating the sensor
startSimulation = millis();
} else {
digitalWrite(triggerPin, LOW); // Ensure the trigger pin goes LOW otherwise
}
// --------------------------------------------------------------------------
}
void activateSensor(){
// Check the sensor input (only if latch is not active)
if (!latchState && digitalRead(triggerPin) == HIGH) {
digitalWrite(sensorLedPin, HIGH);
Serial.println("Motion detected!");
Serial.println("Start latching time...");
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
}
// 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)
digitalWrite(sensorLedPin, LOW); // Turn off the sensor LED explicitly
Serial.println("Motion stopped after latch time.");
}
}