PlantPal Arduino Code | DIY Smart Soil Moisture Monitor - Bambu3Design – 3D Printing & Design
PlantPal Arduino Code | DIY Smart Soil Moisture Monitor

PlantPal Arduino Code | DIY Smart Soil Moisture Monitor

#include <Arduino.h>
#include <Arduino_GFX_Library.h>
#include <EEPROM.h>

// =====================================
// PLANTPAL - ESP8266 D1 MINI
// DISPLAY: NV3007 142x428
// 30 PLANTS + CALIBRATION
// ALWAYS START FROM PLANT 1
// =====================================

// ---------- DISPLAY PINS ----------

#define TFT_DC  D2
#define TFT_CS  D8
#define TFT_RST D1
#define TFT_BL  D0

Arduino_DataBus *bus =
  new Arduino_ESP8266SPI(TFT_DC, TFT_CS);

Arduino_GFX *gfx = new Arduino_NV3007(
  bus, TFT_RST, 0, false,
  142, 428, 12, 0, 14, 0,
  nv3007_279_init_operations,
  sizeof(nv3007_279_init_operations)
);

// ---------- BUTTON PINS ----------

#define BTN_LEFT  D6
#define BTN_RIGHT D4
#define BTN_OK    D3

// ---------- SOIL SENSOR ----------

#define SOIL_PIN A0

// ---------- COLORS ----------

#define BLACK     0x0000
#define WHITE     0xFFFF
#define GREEN     0x07E0
#define DARKGREEN 0x03E0
#define CYAN      0x07FF
#define YELLOW    0xFFE0
#define RED       0xF800
#define GREY      0x8410
#define BROWN     0xA145
#define BG        0x0863
#define PANEL     0x1947

// ---------- PLANT LIST ----------

const char* plants[] = {
  "CACTUS",
  "SUCCULENT",
  "ALOE VERA",
  "SNAKE PLANT",
  "ZZ PLANT",
  "POTHOS",
  "MONSTERA",
  "PHILODENDRON",
  "SPIDER PLANT",
  "RUBBER PLANT",
  "DRACAENA",
  "FICUS",
  "PEACE LILY",
  "CALATHEA",
  "FERN",
  "ORCHID",
  "ANTHURIUM",
  "BEGONIA",
  "GERANIUM",
  "AFRICAN VIOLET",
  "CROTON",
  "YUCCA",
  "ARECA PALM",
  "PARLOR PALM",
  "ENGLISH IVY",
  "AGLAONEMA",
  "DIEFFENBACHIA",
  "PRAYER PLANT",
  "CYCLAMEN",
  "FIDDLE FIG"
};

const int PLANT_COUNT = 30;
const int TOTAL_ITEMS = 31;
const int CALIBRATION_INDEX = 30;

// ---------- EEPROM ----------

#define EEPROM_SIZE 64
#define MAGIC 0x504C414EUL

struct Settings {
  uint32_t magic;
  int dry;
  int wet;
};

Settings settings = {
  MAGIC,
  850,
  250
};

// ---------- SCREEN STATE ----------

enum Screen {
  HOME,
  CALIBRATION_MENU
};

Screen currentScreen = HOME;

// ALWAYS START FROM PLANT 1
int selectedItem = 0;

int menuIndex = 0;

int editDry = 850;
int editWet = 250;

bool measuring = false;

int currentPercent = 0;

unsigned long lastMeasurement = 0;

// ---------- BUTTON STATES ----------

bool leftLock = false;
bool rightLock = false;
bool okLock = false;

// =====================================
// EEPROM
// =====================================

void saveSettings() {

  settings.magic = MAGIC;

  EEPROM.put(0, settings);
  EEPROM.commit();
}

void loadSettings() {

  EEPROM.begin(EEPROM_SIZE);

  Settings stored;
  EEPROM.get(0, stored);

  if (
    stored.magic == MAGIC &&
    stored.dry >= 0 &&
    stored.dry <= 1023 &&
    stored.wet >= 0 &&
    stored.wet <= 1023 &&
    abs(stored.dry - stored.wet) >= 30
  ) {

    settings = stored;
  }

  editDry = settings.dry;
  editWet = settings.wet;
}

// =====================================
// SOIL SENSOR
// =====================================

int readSoilRaw() {

  long total = 0;

  for (int i = 0; i < 10; i++) {

    total += analogRead(SOIL_PIN);
    delay(2);
  }

  return total / 10;
}

int moisturePercent(int raw) {

  if (settings.dry == settings.wet) {
    return 0;
  }

  long value =
    (long)(settings.dry - raw) * 100L /
    (settings.dry - settings.wet);

  return constrain((int)value, 0, 100);
}

// =====================================
// PLANT THRESHOLDS
// =====================================

int plantThreshold(int index) {

  // LOW WATER PLANTS

  if (
    index == 0 ||
    index == 1 ||
    index == 2 ||
    index == 3 ||
    index == 4 ||
    index == 21
  ) {
    return 20;
  }

  // HIGH WATER PLANTS

  if (
    index == 12 ||
    index == 13 ||
    index == 14 ||
    index == 15 ||
    index == 17 ||
    index == 18 ||
    index == 19 ||
    index == 27 ||
    index == 28
  ) {
    return 45;
  }

  return 35;
}

// =====================================
// CENTER TEXT
// =====================================

void centerText(
  String text,
  int y,
  uint16_t color,
  int size = 1
) {

  gfx->setTextSize(size);
  gfx->setTextColor(color);

  int width = text.length() * 6 * size;

  int x = (142 - width) / 2;

  if (x < 0) {
    x = 0;
  }

  gfx->setCursor(x, y);
  gfx->print(text);
}

// =====================================
// DRAW PLANT
// =====================================

void drawPlant(bool happy) {

  // STEM

  gfx->fillRect(
    68, 179, 6, 78, DARKGREEN
  );

  // LEAVES

  gfx->fillEllipse(
    51, 192, 22, 11, GREEN
  );

  gfx->fillEllipse(
    91, 189, 22, 11, GREEN
  );

  gfx->fillEllipse(
    52, 219, 19, 10, GREEN
  );

  gfx->fillEllipse(
    90, 217, 19, 10, GREEN
  );

  gfx->fillEllipse(
    71, 164, 13, 24, GREEN
  );

  // POT

  gfx->fillRoundRect(
    42, 251, 58, 55, 7, BROWN
  );

  gfx->fillRoundRect(
    37, 246, 68, 13, 4, BROWN
  );

  // EYES

  gfx->fillCircle(
    59, 273, 3, BLACK
  );

  gfx->fillCircle(
    83, 273, 3, BLACK
  );

  // MOUTH

  if (happy) {

    gfx->drawLine(
      61, 285, 66, 291, BLACK
    );

    gfx->drawLine(
      66, 291, 76, 291, BLACK
    );

    gfx->drawLine(
      76, 291, 82, 285, BLACK
    );

  } else {

    gfx->drawLine(
      61, 294, 66, 288, BLACK
    );

    gfx->drawLine(
      66, 288, 76, 288, BLACK
    );

    gfx->drawLine(
      76, 288, 82, 294, BLACK
    );
  }
}

// =====================================
// HOME SCREEN
// =====================================

void drawHome() {

  gfx->fillScreen(BG);

  centerText(
    "PlantPal", 18, GREEN, 2
  );

  gfx->drawFastHLine(
    10, 51, 122, GREY
  );

  // CALIBRATION ITEM

  if (selectedItem == CALIBRATION_INDEX) {

    centerText(
      "31 / 31", 76, WHITE
    );

    centerText(
      "CALIBRATION", 130, CYAN
    );

    centerText(
      "SENSOR SETTINGS", 190, WHITE
    );

    centerText(
      "DRY: " + String(settings.dry),
      250,
      YELLOW
    );

    centerText(
      "WET: " + String(settings.wet),
      275,
      YELLOW
    );

    centerText(
      "PRESS OK", 340, GREEN
    );

    centerText(
      "TO OPEN", 360, GREEN
    );

  } else {

    centerText(
      String(selectedItem + 1) + " / 31",
      72,
      WHITE
    );

    centerText(
      "SELECT PLANT",
      94,
      WHITE
    );

    String name = plants[selectedItem];

    centerText(
      name,
      125,
      CYAN,
      name.length() <= 11 ? 2 : 1
    );

    if (measuring) {

      bool happy =
        currentPercent >=
        plantThreshold(selectedItem);

      drawPlant(happy);

      centerText(
        "SOIL MOISTURE",
        323,
        WHITE
      );

      centerText(
        String(currentPercent) + "%",
        341,
        CYAN,
        3
      );

      centerText(
        happy ?
        "NO WATER NEEDED" :
        "NEEDS WATER",
        385,
        happy ? GREEN : YELLOW
      );

    } else {

      drawPlant(true);

      centerText(
        "PRESS OK TO TEST",
        335,
        WHITE
      );
    }
  }

  centerText(
    "<    OK    >",
    407,
    GREY
  );
}

// =====================================
// CALIBRATION MENU
// =====================================

const char* menuItems[] = {
  "Set Dry Soil",
  "Set Wet Soil",
  "Save & Exit",
  "Cancel"
};

void drawCalibration() {

  gfx->fillScreen(BG);

  centerText(
    "PlantPal", 16, GREEN, 2
  );

  centerText(
    "CALIBRATION", 54, CYAN
  );

  gfx->drawFastHLine(
    10, 80, 122, GREY
  );

  for (int i = 0; i < 4; i++) {

    int y = 105 + i * 48;

    if (i == menuIndex) {

      gfx->fillRoundRect(
        5, y - 8, 132, 35, 5, PANEL
      );
    }

    gfx->setTextSize(1);

    gfx->setTextColor(
      i == menuIndex ?
      YELLOW : WHITE
    );

    gfx->setCursor(12, y);

    gfx->print(
      i == menuIndex ? "> " : "  "
    );

    gfx->print(menuItems[i]);
  }

  centerText(
    "DRY: " + String(editDry),
    319,
    WHITE
  );

  centerText(
    "WET: " + String(editWet),
    342,
    WHITE
  );

  centerText(
    "LEFT / RIGHT",
    381,
    GREY
  );

  centerText(
    "OK TO SELECT",
    399,
    GREY
  );
}

// =====================================
// MESSAGE
// =====================================

void showMessage(
  String title,
  String value,
  uint16_t color
) {

  gfx->fillScreen(BG);

  centerText(
    title, 130, WHITE
  );

  centerText(
    value, 174, color, 3
  );

  delay(800);
}

// =====================================
// LEFT ACTION
// =====================================

void actionLeft() {

  Serial.println("LEFT PRESSED");

  if (currentScreen == CALIBRATION_MENU) {

    menuIndex =
      (menuIndex + 3) % 4;

    drawCalibration();

  } else {

    selectedItem =
      (selectedItem + TOTAL_ITEMS - 1)
      % TOTAL_ITEMS;

    measuring = false;

    drawHome();
  }
}

// =====================================
// RIGHT ACTION
// =====================================

void actionRight() {

  Serial.println("RIGHT PRESSED");

  if (currentScreen == CALIBRATION_MENU) {

    menuIndex =
      (menuIndex + 1) % 4;

    drawCalibration();

  } else {

    selectedItem =
      (selectedItem + 1)
      % TOTAL_ITEMS;

    measuring = false;

    drawHome();
  }
}

// =====================================
// OK ACTION
// =====================================

void actionOK() {

  Serial.println("OK PRESSED");

  // CALIBRATION MENU

  if (currentScreen == CALIBRATION_MENU) {

    // SET DRY

    if (menuIndex == 0) {

      editDry = readSoilRaw();

      showMessage(
        "DRY SOIL",
        String(editDry),
        CYAN
      );

      drawCalibration();
    }

    // SET WET

    else if (menuIndex == 1) {

      editWet = readSoilRaw();

      showMessage(
        "WET SOIL",
        String(editWet),
        CYAN
      );

      drawCalibration();
    }

    // SAVE

    else if (menuIndex == 2) {

      if (
        abs(editDry - editWet) < 30
      ) {

        showMessage(
          "VALUES TOO CLOSE",
          "ERROR",
          RED
        );

        drawCalibration();
        return;
      }

      settings.dry = editDry;
      settings.wet = editWet;

      saveSettings();

      showMessage(
        "CALIBRATION",
        "SAVED",
        GREEN
      );

      currentScreen = HOME;
      measuring = false;

      drawHome();
    }

    // CANCEL

    else if (menuIndex == 3) {

      editDry = settings.dry;
      editWet = settings.wet;

      currentScreen = HOME;
      measuring = false;

      drawHome();
    }

    return;
  }

  // OPEN CALIBRATION

  if (
    selectedItem ==
    CALIBRATION_INDEX
  ) {

    currentScreen =
      CALIBRATION_MENU;

    menuIndex = 0;

    editDry = settings.dry;
    editWet = settings.wet;

    drawCalibration();
    return;
  }

  // MEASURE SOIL

  measuring = true;

  int raw = readSoilRaw();

  currentPercent =
    moisturePercent(raw);

  lastMeasurement = millis();

  Serial.print("RAW: ");
  Serial.println(raw);

  Serial.print("MOISTURE: ");
  Serial.println(currentPercent);

  drawHome();
}

// =====================================
// BUTTON CONTROL
// SAME SIMPLE METHOD AS WORKING TEST
// =====================================

void processButtons() {

  // LEFT

  if (digitalRead(BTN_LEFT) == LOW) {

    if (!leftLock) {

      leftLock = true;

      actionLeft();
    }

  } else {

    leftLock = false;
  }

  // RIGHT

  if (digitalRead(BTN_RIGHT) == LOW) {

    if (!rightLock) {

      rightLock = true;

      actionRight();
    }

  } else {

    rightLock = false;
  }

  // OK

  if (digitalRead(BTN_OK) == LOW) {

    if (!okLock) {

      okLock = true;

      actionOK();
    }

  } else {

    okLock = false;
  }
}

// =====================================
// SETUP
// =====================================

void setup() {

  Serial.begin(115200);

  // DISPLAY INITIALIZATION

  gfx->begin();

  pinMode(
    TFT_BL,
    OUTPUT
  );

  digitalWrite(
    TFT_BL,
    HIGH
  );

  // BUTTONS

  pinMode(
    BTN_LEFT,
    INPUT_PULLUP
  );

  pinMode(
    BTN_RIGHT,
    INPUT_PULLUP
  );

  pinMode(
    BTN_OK,
    INPUT_PULLUP
  );

  // LOAD CALIBRATION

  loadSettings();

  // ALWAYS START FROM PLANT 1

  selectedItem = 0;

  currentScreen = HOME;

  measuring = false;

  // INITIAL BUTTON STATES

  leftLock = false;
  rightLock = false;
  okLock = false;

  drawHome();

  Serial.println(
    "PlantPal Ready"
  );

  Serial.println(
    "Starting from Plant 1"
  );
}

// =====================================
// LOOP
// =====================================

void loop() {

  processButtons();

  // AUTOMATIC MOISTURE UPDATE

  if (
    currentScreen == HOME &&
    selectedItem != CALIBRATION_INDEX &&
    measuring &&
    millis() - lastMeasurement >= 2000
  ) {

    lastMeasurement = millis();

    int raw = readSoilRaw();

    int percent =
      moisturePercent(raw);

    if (
      abs(percent - currentPercent) >= 2
    ) {

      currentPercent = percent;

      drawHome();
    }
  }

  delay(5);
}
Scroll to Top