Brewhouse/lib/slowPWM/slowPWM.h
2023-01-25 21:00:25 -05:00

43 lines
984 B
C++
Executable File

#ifndef SLOWPWM_h
#define SLOWPWM_h
#include <Arduino.h>
class slowPWM {
private:
byte outputPin;
unsigned long period;
unsigned long lastSwitchTime;
byte outputState;
public:
void begin(byte pin, unsigned long per) {
outputPin = pin;
period = per;
lastSwitchTime = 0;
outputState = LOW;
pinMode(pin, OUTPUT);
Serial.println("Setup PWM");
}
byte compute(byte duty) {
unsigned long onTime = (duty * period) / 100;
unsigned long offTime = period - onTime;
unsigned long currentTime = millis();
if (duty == 0) {
outputState = LOW;
} else if (outputState == HIGH && (currentTime - lastSwitchTime >= onTime)) {
lastSwitchTime = currentTime;
outputState = LOW;
} else if (outputState == LOW && (currentTime - lastSwitchTime >= offTime)) {
lastSwitchTime = currentTime;
outputState = HIGH;
}
return outputState;
}
};
#endif