Skip to content

Instantly share code, notes, and snippets.

@peltho
Last active July 20, 2023 19:04
Show Gist options
  • Save peltho/b0cbbf84d2a55f9485af2ac7527b2549 to your computer and use it in GitHub Desktop.
Save peltho/b0cbbf84d2a55f9485af2ac7527b2549 to your computer and use it in GitHub Desktop.
Arduino moisture sensor sketch
#include <Arduino.h>
#define MOIST_PIN_1 A5
#define MOIST_PIN_2 A4
#define MOIST_PIN_3 A3
#define MOIST_PIN_4 A2
#define MOIST_PIN_5 A1
#define PWRBTN 7
#define RELAYPIN 5
byte lastButtonState = LOW;
unsigned long debounceDuration = 50; // millis
unsigned long lastTimeButtonStateChanged = 0;
int incomingByte = 0;
char subject1[] = "Philodendron"; // TODO: reorder
char subject2[] = "Alocasia";
char subject3[] = "Monstera";
char subject4[] = "Basil";
char subject5[] = "Pilea";
void setup() {
pinMode(PWRBTN, INPUT);
pinMode(RELAYPIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
// Receiving instruction from Serial port
if (Serial.available() > 0) {
incomingByte = Serial.read();
digitalWrite(RELAYPIN, HIGH);
delay(1000);
measure_moist(MOIST_PIN_1, subject1);
measure_moist(MOIST_PIN_2, subject2);
measure_moist(MOIST_PIN_3, subject3);
measure_moist(MOIST_PIN_4, subject4);
measure_moist(MOIST_PIN_5, subject5);
digitalWrite(RELAYPIN, LOW);
}
// Receiving instruction from Button
if (millis() - lastTimeButtonStateChanged > debounceDuration) {
byte buttonState = digitalRead(PWRBTN);
if (buttonState != lastButtonState) {
lastTimeButtonStateChanged = millis();
lastButtonState = buttonState;
if (buttonState == LOW) {
digitalWrite(RELAYPIN, HIGH);
delay(1000);
measure_moist(MOIST_PIN_1, subject1);
measure_moist(MOIST_PIN_2, subject2);
measure_moist(MOIST_PIN_3, subject3);
measure_moist(MOIST_PIN_4, subject4);
measure_moist(MOIST_PIN_5, subject5);
digitalWrite(RELAYPIN, LOW);
}
}
}
}
void measure_moist(int pin, char name[]) {
int moistV;
long humanReadableValue;
delay(500);
moistV = analogRead(pin);
// Theorical values: map(moistV, 203, 1023, 100, 0);
humanReadableValue = map(moistV, 220, 750, 100, 0);
Serial.print("Subject: ");
Serial.println(name);
Serial.print("> Moisture level (%): ");
Serial.println(humanReadableValue);
}
@peltho
Copy link
Author

peltho commented Jul 10, 2023

Measurement is made at button click.
Waiting for relay to be able to power off sensor at idle time.

Update: Added relay + remote activation

@peltho
Copy link
Author

peltho commented Jul 20, 2023

Added more sensors

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment