Created
August 12, 2022 16:22
-
-
Save magicleon94/580aab1febfcdaa50b458fb1aa5ec49f to your computer and use it in GitHub Desktop.
Read soil humidity and enable a water pump to give water
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Calibration values | |
const int AIR_VALUE = 831; | |
const int WATER_VALUE = 434; | |
// Pin values | |
const int SOIL = A0; | |
const int PUMP = 1; | |
// Thresholds & time intervals | |
const long HUMIDITY_THRESHOLD = 30; // 30% soil humidity | |
const long WATERING_INTERVAL_MS = 3600 * 1000; // 1 hour | |
const long LOOP_INTERVAL_MS = 300 * 1000; //5 minutes | |
// State variables | |
long lastWaterGiven = 0; | |
void setup() { | |
Serial.begin(9600); | |
pinMode(PUMP, OUTPUT); | |
pinMode(SOIL, INPUT); | |
} | |
void loop() { | |
delay(LOOP_INTERVAL_MS); | |
long humidityPercentage = getHumidityPercentage(); | |
reportHumidityPercentage(humidityPercentage); | |
if (shouldGiveWater(humidityPercentage)){ | |
giveWater(); | |
reportWaterGiven(); | |
} | |
} | |
void giveWater(){ | |
digitalWrite(PUMP, HIGH); | |
delay(2000); | |
digitalWrite(PUMP, LOW); | |
// Record last time we gave water | |
lastWaterGiven = millis(); | |
} | |
bool shouldGiveWater(long humidityPercentage){ | |
long now = millis(); | |
return humidityPercentage <= HUMIDITY_THRESHOLD && now | |
} | |
long getHumidityPercentage(){ | |
int sensorValue = analogRead(A0); | |
return map(sensorValue, WATER_VALUE, AIR_VALUE, 100, 0); | |
} | |
void reportHumidityPercentage(long humidityPercentage){ | |
// Stub method, will write to TX and let the bridge report to HomeAssistant | |
Serial.print(humidityPercentage); | |
} | |
void reportWaterGiven(){ | |
// Stub method, will write to TX and let the bridge report to HomeAssistant | |
Serial.print("Water given!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment