/*
Smooth PWM
2024-09-04 by noiasca
2024-09-04 https://forum.arduino.cc/t/analog-ramping-like-a-variable-speed-drive/1298080/6
code not in thread
*/
constexpr uint8_t outputPin {3}; // GPIO for PWM 3, 5, 6, 9, 10, 11 https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/
constexpr uint8_t inputPin {A0}; // GPIO for input
// make your own class for smooth PWM outputs
class SmoothPWM {
protected:
const uint8_t pin; // the pin
uint16_t intervalUp {12}; // "delay" for increase
uint16_t intervalDown {4}; // "delay" for decrease
uint16_t current {0}; // current PWM
uint16_t target {0}; // target PWM
uint32_t previousMillis {0}; // time management - last PWM change
public:
SmoothPWM (const uint8_t pin) : pin(pin) {}
void begin() {
pinMode(pin, OUTPUT);
analogWrite(pin, current);
}
// set a new output target value
void set(uint16_t target) {
if (target > 255) return; // sanitize input
this->target = target;
//Serial.print("target="); Serial.println(this->target);
}
// the run method to be called in loop
void update(uint32_t currentMillis = millis()) {
if ((current < target) && (currentMillis - previousMillis > intervalUp)) { // increase PWM
previousMillis = currentMillis;
current++;
analogWrite(pin, current);
Serial.print("up "); Serial.println(current); // just for debug/demo - comment it out if you see it works
}
else if ((current > target) && (currentMillis - previousMillis > intervalDown)) { // decrease PWM
previousMillis = currentMillis;
current--;
analogWrite(pin, current);
Serial.print("down "); Serial.println(current); // just for debug/demo - comment it out if you see it works
}
}
};
SmoothPWM smoothPWM(outputPin); // create the object
void setup() {
Serial.begin(115200);
smoothPWM.begin(); // start the object
}
void handleInput() {
int adc = analogRead(inputPin);// 0 ... 1023 on an UNO
adc = adc / 4; // PWM is only 0 ... 255
smoothPWM.set(adc); // set as new target
}
void loop() {
handleInput(); // a) get data from (user) interface
smoothPWM.update(); // b) call background task for SmoothPWM object
}
//