Helligkeit/src/patrix/PWMOutput.h

52 lines
973 B
C++

#ifndef PWM_OUTPUT_H
#define PWM_OUTPUT_H
#define CONTROL_PWM_BITS 10
#define CONTROL_PWM_MAX (static_cast<int>(pow(2, CONTROL_PWM_BITS) - 1))
class PWMOutput {
const uint8_t gpio;
String name;
uint32_t frequency = 0;
int value = 0;
double percent = 0;
public:
explicit PWMOutput(const uint8_t gpio, String name, uint32_t frequency) : gpio(gpio), name(std::move(name)), frequency(frequency) {
//
}
void setup() {
analogWriteResolution(CONTROL_PWM_BITS);
analogWriteFreq(frequency);
setValue(0);
}
void setValue(const int v) {
value = max(0, min(CONTROL_PWM_MAX, v));
percent = 100.0 * value / CONTROL_PWM_MAX;
analogWrite(gpio, value);
}
void setPercent(const double newPercent) {
setValue(static_cast<int>(newPercent / 100.0 * CONTROL_PWM_MAX));
}
[[nodiscard]] double getPercent() const {
return percent;
}
[[nodiscard]] int getValue() const {
return value;
}
};
#endif