fishtankmonitor/sensors.cpp

57 lines
No EOL
1.5 KiB
C++

#include "sensors.h"
#include <Arduino.h>
Sensors::Sensors(int temperaturePin, char *temperatureTopic, char *phTopic, Networking* networking, DallasTemperature* ds18b20) {
_networking = networking;
//OneWire oneWire = OneWire(temperaturePin);
//_ds18b20 = DallasTemperature(&oneWire);
_ds18b20 = ds18b20;
_temperaturePin = temperaturePin;
_temperatureTopic = temperatureTopic;
_phTopic = phTopic;
}
void Sensors::setup() {
pinMode(_temperaturePin, INPUT_PULLUP);
_ds18b20->begin();
_ads.setGain(GAIN_TWOTHIRDS);
_ads.begin();
}
float Sensors::readpH() {
int sum = 0;
const int readCount = 10;
for (int i = 0; i < readCount; i++) {
sum += _ads.readADC_SingleEnded(0);
delay(10);
}
float averageRead = float(sum) / readCount;
float voltage = 6.144 / 32768.0 * averageRead;
voltage -= VOLTAGE_OFFSET;
Serial.println(voltage);
float pH = 7 - ((PH_7_VOLTAGE - voltage) / _pHStep);
return pH;
}
void Sensors::publishpH() {
float pH = readpH();
String pHString(pH, 2);
_networking->publish(_phTopic, pHString.c_str(), true);
}
void Sensors::publishTemperature() {
_ds18b20->requestTemperatures();
float temperature = _ds18b20->getTempCByIndex(0);
int attemptStart = millis();
while ((temperature == 85 || temperature == -127)){
Serial.println(temperature);
if (attemptStart - millis() > 1000)
return;
temperature = _ds18b20->getTempCByIndex(0);
}
String temperatureString(temperature, 2);
_networking->publish(_temperatureTopic, temperatureString.c_str(), true);
}