/ M4_Eyes / user_pir.cpp
user_pir.cpp
 1  // SPDX-FileCopyrightText: 2020 Phillip Burgess for Adafruit Industries
 2  //
 3  // SPDX-License-Identifier: MIT
 4  
 5  #if 0 // Change to 1 to enable this code (must enable ONE user*.cpp only!)
 6  
 7  // PIR motion sensor on pin 3 makes eyes open when motion is detected.
 8  
 9  #include "globals.h"
10  
11  #define PIR_PIN 3  // PIR sensor on D3 connector (between MIC & BAT)
12  
13  static uint8_t priorState;
14  
15  void user_setup(void) {
16    pinMode(PIR_PIN, INPUT);
17    priorState = digitalRead(PIR_PIN);
18    for(uint8_t e=0; e<NUM_EYES; e++) {
19      // Init to DEBLINK with an impossibly large duration to hold eyes shut.
20      eye[e].blink.state     = DEBLINK;
21      eye[e].blink.duration  = 0x7FFFFFFF;
22      eye[e].blink.startTime = micros();
23    }
24  }
25  
26  void user_loop(void) {
27    uint8_t e, newState = digitalRead(PIR_PIN);
28    if(newState != priorState) {
29      if(newState) {
30        // Initial motion sensed
31        for(e=0; e<NUM_EYES; e++) {          // For each eye...
32          eye[e].blink.state     = DEBLINK;  // Opening...
33          eye[e].blink.duration  = 500000;   // Slowly, about 1/2 sec
34          eye[e].blink.startTime = micros(); // Starting now
35        }
36      } else {
37        // PIR timeout; "end" of motion
38        for(e=0; e<NUM_EYES; e++) {            // For each eye...
39          if(eye[e].blink.state != ENBLINK) {  // If not already blinking...
40            eye[e].blink.state     = ENBLINK;  // Start closing...
41            eye[e].blink.duration  = 1500000;  // Even slower, about 1.5 sec
42            eye[e].blink.startTime = micros(); // Starting now
43          }
44        }
45      }
46      priorState = newState;
47    } else if(!newState) {
48      // No change in state. If currently no motion active,
49      // force eyes into closed position at every opportunity.
50      for(e=0; e<NUM_EYES; e++) {           // For each eye...
51        if(eye[e].blink.state != ENBLINK) { // If not currently blinking...
52          // Set to DEBLINK with an impossibly large duration -- eyes will
53          // hold shut until motion event above resets start & duration.
54          eye[e].blink.state     = DEBLINK;
55          eye[e].blink.duration  = 0x7FFFFFFF;
56          eye[e].blink.startTime = micros();
57        }
58      }
59    }
60  }
61  
62  #endif // 0