Here how it should work:
Code: Select all
typedef struct
{
unsigned long refTime;
int pin;
float m;
float q;
float current;
float duration;
bool ended;
} Led_t;
Led_t led;
void led_fade(float target, float duration)
{
if (target < 0.0) target = 0.0;
target = target * 255.0 / 100.0;
if (target > 255.0) target = 255.0;
if (duration < 0) duration = 0;
_led.refTime = millis();
_led.duration = duration;
_led.ended = false;
_led.m = (target - _led.current) / duration;
_led.q = _led.current;
}
void process_led()
{
unsigned long currTime = millis();
float t = ((float)currTime - _led.refTime) / 1000.0;
if (t < _led.duration)
{
_led[i].current = _led.m * t + _led.q;
analogWrite(_led.pin, _led.current);
}
else
{
if (!_led.ended)
{
_led.ended = true;
}
}
}
Code: Select all
void setup()
{
unsigned long currTime = millis();
_led.refTime = currTime;
_led.current = 0;
_led.pin = LED_PIN;
_led.ended = true;
analogWrite(_led.pin, _led.current);
}
void loop()
{
process_led();
//when some conditions met:
led_fade(100.0, 5.0);
I may use the HardwareTimer but this is just a simple example.
In the real code, I have all the 20 pins pwm-ready for Nucleo F429ZI board and the user may select at run-time how many of them control in PWM.
Or I can pass any "pwm" pin to `setPWM` function?