Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. /*
  2. A Photon sketch for detecting motion.
  3.  
  4. This sketch will fire an event when motion is detected, and when it is lost.
  5. The motion timeout is done by the PIR sensor.
  6. */
  7. const int LED = D7;
  8. const int PIR1 = D4;
  9. const int PIR2 = D5;
  10.  
  11. const int TTL = 60; // this doesn't actually do anything, but is required.
  12.  
  13. // The minimum interval between consectutive events of the same type
  14. const int PUBLISH_EVENT_MIN_INTERVAL = 30; // seconds
  15.  
  16. const int MOTION_DETECTED = 2;
  17. const int MOTION_TIMEOUT = 1;
  18.  
  19. int lastPirReading = -1;
  20.  
  21. int lastPublishedAt = 0;
  22. int lastPublishedEventType = 0;
  23.  
  24. void setup() {
  25. pinMode(LED, OUTPUT);
  26. pinMode(PIR1, INPUT);
  27. pinMode(PIR2, INPUT);
  28. }
  29.  
  30. void loop() {
  31. int reading = pirReading();
  32. if (reading != lastPirReading) {
  33. if (reading == HIGH) {
  34. motionDetected();
  35. } else {
  36. motionTimeout();
  37. }
  38. lastPirReading = reading;
  39. }
  40. }
  41.  
  42. int pirReading() {
  43. int pir1Reading = digitalRead(PIR1);
  44. int pir2Reading = digitalRead(PIR2);
  45.  
  46. if (pir1Reading == HIGH || pir2Reading == HIGH) {
  47. return HIGH;
  48. } else {
  49. return LOW;
  50. }
  51. }
  52.  
  53. void motionDetected() {
  54. digitalWrite(LED, HIGH);
  55.  
  56. publish(MOTION_DETECTED);
  57. }
  58.  
  59. void motionTimeout() {
  60. digitalWrite(LED, LOW);
  61.  
  62. publish(MOTION_TIMEOUT);
  63. }
  64.  
  65. bool canPublish(int eventType) {
  66. if (eventType != lastPublishedEventType) {
  67. return true;
  68. } else {
  69. int currentTime = Time.now();
  70. return (currentTime - lastPublishedAt) > PUBLISH_EVENT_MIN_INTERVAL;
  71. }
  72. }
  73.  
  74. bool publish(int eventType) {
  75. if (canPublish(eventType)) {
  76. String name = eventName(eventType);
  77.  
  78. bool success = Particle.publish(name, NULL, TTL, PRIVATE);
  79. if (success) {
  80. lastPublishedAt = Time.now();
  81. lastPublishedEventType = eventType;
  82. }
  83. return success;
  84. }
  85. return false;
  86. }
  87.  
  88. String eventName(int eventType) {
  89. String name = "error";
  90. switch (eventType) {
  91. case MOTION_TIMEOUT:
  92. name = "motion-timeout";
  93. break;
  94. case MOTION_DETECTED:
  95. name = "motion-detected";
  96. break;
  97. }
  98. return name;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement