Browse Source

Committing totally untested code for a PIR sensor class with timing independent of sensor.

Robert Marshall 5 years ago
parent
commit
8b6e5efe2c
1 changed files with 35 additions and 0 deletions
  1. 35 0
      Transmitter/src/PIR.cpp

+ 35 - 0
Transmitter/src/PIR.cpp

@@ -0,0 +1,35 @@
+#include <Arduino.h>
+
+class PIR{
+	unsigned int _pin;
+	unsigned long _triggerDuration, _motionDetectedTime;
+	bool _currentMotionState;
+	void (*_startCallback)(void);
+	void (*_stopCallback)(void);
+
+public:
+	PIR(unsigned int pin, unsigned long triggerDuration,  void (*startCallback)(void), void (*stopCallback)(void)){
+		_pin = pin;
+		_triggerDuration = triggerDuration;
+		_startCallback = startCallback;
+		_stopCallback = stopCallback;
+
+		pinMode(_pin, INPUT);
+	}
+
+	void loop(){
+		bool motionDetected = digitalRead(_pin) == HIGH;
+
+		if (motionDetected) {
+			_motionDetectedTime = mllis();
+			if (!_currentMotionState)
+				_startCallback();
+			_currentMotionState = motionDetected;
+		}
+
+		if (_currentMotionState && millis() >= _motionDetectedTime + _triggerDuration){
+			_stopCallback();
+			_currentMotionState = false;
+		}
+	}
+};