esp-volumeknob/src/esp-volumeknob.cpp

110 lines
2.9 KiB
C++

#include <Homie.h>
#include <ArduinoOTA.h>
#include <Encoder.h> //Library download: https://github.com/PaulStoffregen/Encoder
#include "DHT.h"
DHT dht(D1,DHT22);
float temperature=0;
float humidity=0;
double lastSensorMillis=0;
#define SENSORPERIOD 5000
//D4 auf ground macht led leuchten
#define PIN_ENCA D6
#define PIN_ENCB D5
#define PIN_BTN D2
#define POSITIONUPDATE 100
Bounce debouncerKnobBTN = Bounce();
int lastKnobBTN = -1;
Encoder myEnc(PIN_ENCA, PIN_ENCB);
long lastPositionCheck=0;
long oldPosition = 0;
// HomieNode knobNode("volumeknob", "Volumeknob");
HomieNode knobNode("volumeknob", "Volumeknob", "commands");
// HomieNode homieNode("pixel", "pixel", "commands");
void loopHandler() {
int valueKnobBTN = debouncerKnobBTN.read();
if (valueKnobBTN != lastKnobBTN) {
Homie.getLogger() << "KnobButton is now " << (valueKnobBTN ? "open" : "close") << endl;
knobNode.setProperty("btnknob").send(valueKnobBTN ? "false" : "true");
lastKnobBTN = valueKnobBTN;
}
long newPosition = myEnc.read()/4;
if ((unsigned long)(lastPositionCheck+POSITIONUPDATE) < millis() && newPosition != oldPosition) {
long positiondiff=newPosition-oldPosition;
oldPosition = newPosition;
Homie.getLogger() << "posdiff= " << positiondiff << endl;
knobNode.setProperty("encoder").send(String(positiondiff));
lastPositionCheck=millis();
}
if ((lastSensorMillis+SENSORPERIOD)<millis()){
float _currentTemperature=dht.readTemperature();
if (temperature!=_currentTemperature && (!isnan(_currentTemperature) ==1) && _currentTemperature>-40){
temperature=_currentTemperature;
Homie.getLogger() << "temperature= " << temperature << endl;
char tempstring[16];
dtostrf(temperature,1,1,tempstring);
knobNode.setProperty("temperature").send(tempstring);
}
float _currentHumidity=dht.readHumidity();
if (humidity!=_currentHumidity && (!isnan(_currentHumidity) ==1) && _currentHumidity>0){
humidity=_currentHumidity;
Homie.getLogger() << "humidity= " << humidity << endl;
knobNode.setProperty("humidity").send(String(humidity));
}
lastSensorMillis=millis();
}
ArduinoOTA.handle();
}
void setup() {
Serial.begin(115200);
Serial << endl << endl;
pinMode(PIN_BTN, INPUT_PULLUP);
debouncerKnobBTN.attach(PIN_BTN);
debouncerKnobBTN.interval(50);
Homie_setFirmware("volumeknob", "0.1.0");
//Homie.setResetTrigger(PIN_BTN, LOW, 20000); // BTN0 = Flash = PIN_BTN set to 20sec
Homie.disableResetTrigger();
Homie.setLoopFunction(loopHandler);
knobNode.advertise("encoder");
knobNode.advertise("btnknob");
knobNode.advertise("temperature");
knobNode.advertise("humidity");
Homie.setup();
ArduinoOTA.setHostname(Homie.getConfiguration().deviceId);
ArduinoOTA.onStart([]() {
Homie.getLogger() << "Arduino OTA angefragt" << endl;
});
ArduinoOTA.begin();
}
void loop() {
Homie.loop();
debouncerKnobBTN.update();
}