time instead of iteration for turning off light
This commit is contained in:
@@ -6,7 +6,8 @@
|
||||
// Normal mode command
|
||||
#define COMMAND "FDFCFBFA0800120000006400000004030201"
|
||||
#define PRESENCE_DISTANCE 100
|
||||
#define COUNT_STATUS_DIFFERENCE 5
|
||||
#define DELAY_STATUS_CHECK 1000 // delay (in ms) between two checks of the presence
|
||||
#define POWER_DELAY 20000 // delay (in ms) until turning off the screen
|
||||
|
||||
// Zigbee
|
||||
#define OCCUPANCY_SENSOR_ENDPOINT_NUMBER 1
|
||||
@@ -14,7 +15,7 @@
|
||||
ZigbeeOccupancySensor zbOccupancySensor = ZigbeeOccupancySensor(OCCUPANCY_SENSOR_ENDPOINT_NUMBER);
|
||||
|
||||
bool isPresent = false;
|
||||
int countDifferent = 0;
|
||||
unsigned long lastMotionDetected = 0; // time when the last motion was detected
|
||||
|
||||
void setup() {
|
||||
initSerial();
|
||||
@@ -25,7 +26,7 @@ void setup() {
|
||||
|
||||
void loop() {
|
||||
readAndProcessSensorLines();
|
||||
delay(500);
|
||||
delay(DELAY_STATUS_CHECK);
|
||||
}
|
||||
|
||||
void initSerial() {
|
||||
@@ -95,25 +96,24 @@ void readAndProcessSensorLines() {
|
||||
|
||||
// Check if the line contains the "Range" information
|
||||
if (line.startsWith("Range ")) {
|
||||
|
||||
// Extract the substring after "Range "
|
||||
String distanceStr = line.substring(6);
|
||||
int distance = distanceStr.toInt();
|
||||
bool currentStatus = distance <= PRESENCE_DISTANCE;
|
||||
|
||||
if (currentStatus != isPresent) {
|
||||
countDifferent++;
|
||||
} else {
|
||||
countDifferent = 0;
|
||||
if (currentStatus == 1) {
|
||||
lastMotionDetected = millis();
|
||||
}
|
||||
|
||||
// change the status, if the last n updates were different than the current status
|
||||
if (countDifferent >= COUNT_STATUS_DIFFERENCE) {
|
||||
isPresent = !isPresent;
|
||||
if (currentStatus && !isPresent) {
|
||||
isPresent = true;
|
||||
bool res = sendZigbeeOnOffCommand(isPresent);
|
||||
Serial.print("Message sent: ");
|
||||
Serial.print(isPresent);
|
||||
Serial.print(" - successful: ");
|
||||
Serial.println(res);
|
||||
Serial.println("Motion detected, turning screen light on");
|
||||
} else if (!currentStatus && isPresent && (millis() - lastMotionDetected >= POWER_DELAY)) {
|
||||
isPresent = false;
|
||||
bool res = sendZigbeeOnOffCommand(isPresent);
|
||||
Serial.printf("No motion detected for %d ms, turning light off.\n", POWER_DELAY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user