Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* PIR Closet Sensor, with kill switch.
*/
const int relayPin = D1;
const int pirSensor = D2;
const int btnSensor = D8;
int pir = 0; // Variable for pir.
int pirState = LOW; // Start as off.
int btn = 0; // Variable for button.
int btnState = LOW; // Start as off.
void setup() {
Serial.begin( 9600 );
Serial.println();
Serial.println( "Starting up..." );
pinMode( relayPin, OUTPUT );
pinMode( pirSensor, INPUT );
pinMode( btnSensor, INPUT );
}
void loop() {
btn = digitalRead( btnSensor );
pir = digitalRead( pirSensor );
// If a button is pushed, and motion is detected,
// turn off the light and wait until it resets.
if ( HIGH == btn && LOW == btnState && HIGH == pir ) {
digitalWrite( relayPin, LOW );
btnState = HIGH;
Serial.println( "Killswitch detected -- turning off light." );
delay( 1000 );
return;
}
// If the button was pressed, keep shorting
// until the pir goes low again.
if ( HIGH == btnState ) {
if ( LOW == pir ) {
Serial.println( "No motion, resetting state." );
btnState = LOW;
}
if ( HIGH == btn ) {
Serial.println( "Button pressed, turning light back on." );
digitalWrite( relayPin, HIGH );
btnState = LOW;
}
return;
}
// If the pir senses light,
if ( HIGH == pir ) {
digitalWrite( relayPin, HIGH );
if ( LOW == pirState ) {
Serial.println( "Motion detected!" );
pirState = HIGH;
}
} else {
digitalWrite( relayPin, LOW );
if ( HIGH == pirState ) {
Serial.println( "Motion ended." );
pirState = LOW;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment