From 48756874e50fd082305211a16f097731b3189a98 Mon Sep 17 00:00:00 2001 From: calculator Date: Wed, 18 Nov 2020 22:11:37 +0100 Subject: [PATCH] replaced HC-SR04 with SR04M-2 --- esp32/include/ControllerConfiguration.h | 4 --- esp32/src/main.cpp | 41 +++++++++++++++++++------ 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/esp32/include/ControllerConfiguration.h b/esp32/include/ControllerConfiguration.h index 7bdc650..8714a24 100644 --- a/esp32/include/ControllerConfiguration.h +++ b/esp32/include/ControllerConfiguration.h @@ -89,10 +89,6 @@ #define SOLAR_CHARGE_MIN_VOLTAGE 7 /**< Sun is rising (morning detected) */ #define SOLAR_CHARGE_MAX_VOLTAGE 9 /**< Sun is shining (noon) */ -#define HC_SR04 /**< Ultrasonic distance sensor to measure water level */ -#define SENSOR_SR04_ECHO 17 /**< GPIO 17 - Echo */ -#define SENSOR_SR04_TRIG 23 /**< GPIO 23 - Trigger */ - #define MAX_CONFIG_SETTING_ITEMS 50 /**< Parameter, that can be configured in Homie */ #define PANIK_MODE_DEEPSLEEP (60 * 60 * 5U) /**< 5 hours in usecond */ diff --git a/esp32/src/main.cpp b/esp32/src/main.cpp index 8090b06..445fb6d 100644 --- a/esp32/src/main.cpp +++ b/esp32/src/main.cpp @@ -112,6 +112,30 @@ long getLastMoisture(int plantId) } } +long getDistance(){ + unsigned int distance; + byte startByte, h_data, l_data, sum = 0; + byte buf[3]; + + startByte = (byte)Serial.read(); + if(startByte == 255){ + Serial.readBytes(buf, 3); + h_data = buf[0]; + l_data = buf[1]; + sum = buf[2]; + distance = (h_data<<8) + l_data; + if(((startByte + h_data + l_data)&0xFF) != sum){ + return -1; + } + else{ + return distance; + } + } else { + return -2; + } + +} + void readSystemSensors() { for (int i=0; i < 5; i++) { @@ -420,16 +444,13 @@ bool readSensors() /* Use the Ultrasonic sensor to measure waterLevel */ for (int i = 0; i < 5; i++) { - digitalWrite(SENSOR_SR04_TRIG, LOW); - delayMicroseconds(2); - digitalWrite(SENSOR_SR04_TRIG, HIGH); - delayMicroseconds(10); - digitalWrite(SENSOR_SR04_TRIG, LOW); - float duration = pulseIn(SENSOR_SR04_ECHO, HIGH); - waterRawSensor.add((duration * .343) / 2); - Serial << "Distance sensor " << duration << " ms : " << waterRawSensor.getAverage() << " cm" << endl; - delay(20); + while(!Serial.available()){} + unsigned int distance = getDistance(); + if(distance > 0){ + waterRawSensor.add(distance); + } } + Serial << "Distance sensor " << waterRawSensor.getAverage() << " cm" << endl; /* deactivate the sensors */ digitalWrite(OUTPUT_SENSOR, LOW); return leaveMode1; @@ -705,7 +726,7 @@ void mode2() */ void setup() { - Serial.begin(115200); + Serial.begin(9600); Serial.setTimeout(1000); // Set timeout of 1 second Serial << endl << endl;