Trying to replace SerialSoftware in a library

@robpacker

you need to start Serial1 in maintab:

#include "PlantMonitorRob.h"
#include "Arduino.h"

PlantMonitor pm(Serial1);

void setup() {
  Serial.begin(115200);
  Serial1.begin(115200);
  pm.begin();
}

void loop() {
  if (Serial1.available()) {
    char cmd = Serial1.read();
    if (cmd == 'l') {
      pm.ledOff();
    }
    else if (cmd == 'L') {
      pm.ledOn();
    }
  }
  report();
  delay(1000);
}

void report() {
  Serial.print("Wetness: ");
  Serial.print(pm.getWater());
  Serial.print(" temp (C): ");
  Serial.print(pm.getTemp());
  Serial.print(" humidity: ");
  Serial.println(pm.getHumidity());
}

you have to correct the constructor in the .h:

// based on https://github.com/monkmakes/mm_plant_monitor
#ifndef PlantMonitorRob_h         //  updated to avoid library conflicts
#define PlantMonitorRob_h

#include "Arduino.h"

class PlantMonitor
{
  private:
    Stream& stream;
  public:
    int getWater();
    float getTemp();
    float getHumidity();
    void ledOn();
    void ledOff();
    void begin();    // Add a begin method that you can call from setup

  PlantMonitor(Stream &stream) : stream(stream) {}  
};

#endif

stream doesn't have a begin function - hence you can't use begin on the stream reference.
I just have commented it:

//based on https://github.com/monkmakes/mm_plant_monitor
#include "Arduino.h"
#include "PlantMonitorRob.h"

/*
PlantMonitor::PlantMonitor(&Serial1) : stream(&Serial1) {
  stream = HardwareSerial(&Serial1);
  stream.begin(9600);
}
*/

int PlantMonitor::getWater() {
  stream.print("w");
  while (! stream.read() == '=') {};
  return stream.parseInt();
}

float PlantMonitor::getTemp() {
  stream.print("t");
  while (! stream.read() == '=') {};
  return stream.parseFloat();
}

float PlantMonitor::getHumidity() {
  stream.print("h");
  while (! stream.read() == '=') {};
  return stream.parseFloat();
}

void PlantMonitor::ledOn() {
  stream.print("L");
}

void PlantMonitor::ledOff() {
  stream.print("l");
}

void PlantMonitor::begin() {
//    stream.begin(115200); 
}
//

please also activate the verbose output during compilation, there are several warnings regarding the cpp code.

When you dig deeper into the code consider to rewrite the hole thing based on

1 Like