1
0
mirror of https://github.com/esphome/esphome.git synced 2025-03-25 12:08:16 +00:00
esphome/esphome/components/output/float_output.cpp
dubit0 002861f13b
Float output: Fix min_power and max_power adjusting when output is inverted (#1250)
This patch fixes faulty behaviour when both, invert and min_power/max_power
are set for a float output (e.g. PWM). The current code scales the output
level to the range [min_power, max_power] and subsequently inverts the value.
This leads to values that are outside the range [min_power, max_power].

This patch fixes the problem by inverting the requested level first and then
scaling it to the interval [min_power, max_power].

Co-authored-by: Thomas Niederprüm <niederp@physik.uni-kl.de>
2020-10-01 19:55:42 -03:00

42 lines
1.1 KiB
C++

#include "float_output.h"
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
namespace esphome {
namespace output {
static const char *TAG = "output.float";
void FloatOutput::set_max_power(float max_power) {
this->max_power_ = clamp(max_power, this->min_power_, 1.0f); // Clamp to MIN>=MAX>=1.0
}
float FloatOutput::get_max_power() const { return this->max_power_; }
void FloatOutput::set_min_power(float min_power) {
this->min_power_ = clamp(min_power, 0.0f, this->max_power_); // Clamp to 0.0>=MIN>=MAX
}
float FloatOutput::get_min_power() const { return this->min_power_; }
void FloatOutput::set_level(float state) {
state = clamp(state, 0.0f, 1.0f);
#ifdef USE_POWER_SUPPLY
if (state > 0.0f) { // ON
this->power_.request();
} else { // OFF
this->power_.unrequest();
}
#endif
if (this->is_inverted())
state = 1.0f - state;
float adjusted_value = (state * (this->max_power_ - this->min_power_)) + this->min_power_;
this->write_state(adjusted_value);
}
void FloatOutput::write_state(bool state) { this->set_level(state != this->inverted_ ? 1.0f : 0.0f); }
} // namespace output
} // namespace esphome