From 59fc3ff0cbbc5322a6692b3b6671c36a71a957e2 Mon Sep 17 00:00:00 2001 From: chriswin Date: Sun, 19 Oct 2025 20:36:44 +0200 Subject: [PATCH] time instead of iteration for turning off light --- hmmd-sensor-waveshare.ino | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/hmmd-sensor-waveshare.ino b/hmmd-sensor-waveshare.ino index 8f0eee7..9342c74 100644 --- a/hmmd-sensor-waveshare.ino +++ b/hmmd-sensor-waveshare.ino @@ -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); } } }