water-sensor/water_sensor.ino

65 lines
1.1 KiB
Arduino
Raw Normal View History

2024-02-08 21:47:49 +00:00
#define ADC_PIN A0
#define RELAY_PIN 13
#define RELAY_OFF LOW
#define RELAY_ON HIGH
#define NUM_SAMPLES 20
#define SAMPLE_TIME 100
#define WATER_THRESHOLD 750
bool leakDetected = false;
void relayOn() {
Serial.println("Setting relay ON");
digitalWrite(RELAY_PIN, RELAY_ON);
}
void relayOff() {
Serial.println("Setting relay OFF");
digitalWrite(RELAY_PIN, RELAY_OFF);
}
bool sampleWater() {
bool waterDetected = true;
Serial.print("Samples: ");
for (int i = 0; i < NUM_SAMPLES; i++) {
int sample = analogRead(ADC_PIN);
Serial.print(sample);
Serial.print(",\t");
if (sample < WATER_THRESHOLD) {
waterDetected = false;
}
delay(SAMPLE_TIME);
}
Serial.println(waterDetected ? "POS" : "NEG");
return waterDetected;
}
void setup() {
Serial.begin(115200);
//Serial.setDebugOutput(true);
Serial.println();
Serial.println();
Serial.println();
Serial.println("===== BOOT UP =====");
pinMode(RELAY_PIN, OUTPUT);
relayOn();
}
void loop() {
if (sampleWater()) {
Serial.println("Water detected");
relayOff();
} else {
Serial.println("No water");
}
}