// Relay pin is controlled with D8. The active wire is connected to Normally Closed and common
int relay = 8;
volatile byte relayState = LOW;
// PIR Motion Sensor is connected to D2.
int PIRInterrupt = 2;
// 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");
if(relayState == LOW){
digitalWrite(relay, LOW);
}
relayState = HIGH;
Serial.println("ON");
lastDebounceTime = millis();
}
uno:A5.2
uno:A4.2
uno:AREF
uno:GND.1
uno:13
uno:12
uno:11
uno:10
uno:9
uno:8
uno:7
uno:6
uno:5
uno:4
uno:3
uno:2
uno:1
uno:0
uno:IOREF
uno:RESET
uno:3.3V
uno:5V
uno:GND.2
uno:GND.3
uno:VIN
uno:A0
uno:A1
uno:A2
uno:A3
uno:A4
uno:A5
relay1:VCC
relay1:GND
relay1:IN
relay1:NC
relay1:COM
relay1:NO