Created
July 20, 2017 08:59
-
-
Save ajesler/11b2a25a99993fa7a7a1c22567e19737 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
A Photon sketch for detecting motion. | |
This sketch will fire an event when motion is detected, and when it is lost. | |
The motion timeout is done by the PIR sensor. | |
*/ | |
const int LED = D7; | |
const int PIR1 = D4; | |
const int PIR2 = D5; | |
const int TTL = 60; // this doesn't actually do anything, but is required. | |
// The minimum interval between consectutive events of the same type | |
const int PUBLISH_EVENT_MIN_INTERVAL = 30; // seconds | |
const int MOTION_DETECTED = 2; | |
const int MOTION_TIMEOUT = 1; | |
int lastPirReading = -1; | |
int lastPublishedAt = 0; | |
int lastPublishedEventType = 0; | |
void setup() { | |
pinMode(LED, OUTPUT); | |
pinMode(PIR1, INPUT); | |
pinMode(PIR2, INPUT); | |
} | |
void loop() { | |
int reading = pirReading(); | |
if (reading != lastPirReading) { | |
if (reading == HIGH) { | |
motionDetected(); | |
} else { | |
motionTimeout(); | |
} | |
lastPirReading = reading; | |
} | |
} | |
int pirReading() { | |
int pir1Reading = digitalRead(PIR1); | |
int pir2Reading = digitalRead(PIR2); | |
if (pir1Reading == HIGH || pir2Reading == HIGH) { | |
return HIGH; | |
} else { | |
return LOW; | |
} | |
} | |
void motionDetected() { | |
digitalWrite(LED, HIGH); | |
publish(MOTION_DETECTED); | |
} | |
void motionTimeout() { | |
digitalWrite(LED, LOW); | |
publish(MOTION_TIMEOUT); | |
} | |
bool canPublish(int eventType) { | |
if (eventType != lastPublishedEventType) { | |
return true; | |
} else { | |
int currentTime = Time.now(); | |
return (currentTime - lastPublishedAt) > PUBLISH_EVENT_MIN_INTERVAL; | |
} | |
} | |
bool publish(int eventType) { | |
if (canPublish(eventType)) { | |
String name = eventName(eventType); | |
bool success = Particle.publish(name, NULL, TTL, PRIVATE); | |
if (success) { | |
lastPublishedAt = Time.now(); | |
lastPublishedEventType = eventType; | |
} | |
return success; | |
} | |
return false; | |
} | |
String eventName(int eventType) { | |
String name = "error"; | |
switch (eventType) { | |
case MOTION_TIMEOUT: | |
name = "motion-timeout"; | |
break; | |
case MOTION_DETECTED: | |
name = "motion-detected"; | |
break; | |
} | |
return name; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment