smart_garden/src/valve.cpp

67 lines
1.7 KiB
C++

#include <capacitiveSoilMoistureSensor.h>
#include <common.h>
#include <store.h>
extern "C" {
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
}
#include <valve.h>
bool openValve() {
digitalWrite(PIN_VALVE, HIGH);
digitalWrite(PIN_LED_G, LOW);
digitalWrite(PIN_LED_B, HIGH);
return true;
}
bool closeValve() {
digitalWrite(PIN_VALVE, LOW);
digitalWrite(PIN_LED_G, HIGH);
digitalWrite(PIN_LED_B, LOW);
return false;
}
void valveTask(void *parameter) {
bool isAutomatic = (bool)parameter;
Serial.print(isAutomatic);
Serial.println(" Valve task triggered.");
unsigned long valveTimeoutTimer = millis();
bool valveOpen = false;
int initialSoilMoisture = readCapacitiveSoilMoistureSensor();
if (initialSoilMoisture <= permanentWiltingPoint || irrigateUntilFC) {
valveOpen = openValve();
irrigateUntilFC = true;
} else {
Serial.println("Soil contains enough water. No irrigation needed. ");
}
while (valveOpen) {
delay(500);
int mstValue = readCapacitiveSoilMoistureSensor();
if (mstValue > fieldCapacity) { // && isAutomatic
Serial.println("Field capacity reached. No irrigation needed. ");
valveOpen = closeValve();
irrigateUntilFC = false;
}
if (millis() - valveTimeoutTimer >= MAX_VALVE_TIMEOUT) {
Serial.println("Irrigation timeout reached. close valve. ");
valveOpen = closeValve();
}
}
vTaskDelete(NULL);
}
void toggleValve(bool automatic) {
xTaskCreate(
valveTask, /* Task function. */
"valveTask", /* String with name of task. */
2048, /* Stack size in bytes. */
&automatic, /* Parameter passed as input of the task */
3, /* Priority of the task. */
NULL); /* Task handle. */
}