Last active
July 20, 2023 19:04
-
-
Save peltho/b0cbbf84d2a55f9485af2ac7527b2549 to your computer and use it in GitHub Desktop.
Arduino moisture sensor sketch
This file contains 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
#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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Measurement is made at button click.
Waiting for relay to be able to power off sensor at idle time.
Update: Added relay + remote activation