K
K
Kirill2018-12-29 23:26:57
Arduino
Kirill, 2018-12-29 23:26:57

How to make a smooth change in PWM brightness?

Hey! I control the brightness of the tape through MQTT using the examples, I did everything good, but I want the tape to smoothly change the brightness by adding a delay (FADESPEED); as in RGB examples it doesn't work :(

String strPayload = String((char*)payload);  //считываем значение топика
    int val = strPayload.toInt(); //конвертируем для шим
    int stled = map(val, 0, 100, 0, 255); //приводим значение 0-100 в значение 255-0
    analogWrite(LEDPIN, stled); //устанавливаем уровень шим сигнала
    //delay(FADESPEED);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-12-30
@KirillSPB777

I want the tape to smoothly change the brightness

to do this, you need to change the PWM duty cycle not once, jumping from the current value to the target, but gradually, in several steps. At constant speed, something like this:
void set_pwm_smooth(int new_pwm)
{
    static const int pwm_step = ...; // шаг изменения ШИМ
    static const int pwm_step_time = ...; // время одного шага изменения ШИМ
    static int old_pwm;
    int pwm = old_pwm;

    while (pwm != new_pwm) {
        int next_pwm = pwm + (pwm < new_pwm ? pwm_step : -pwm_step);
        if ((pwm < new_pwm && next_pwm > new_pwm) ||
            (pwm > new_pwm && next_pwm < new_pwm))
            pwm = new_pwm;
        else
            pwm = next_pwm;
        analogWrite(LEDPIN, pwm);
        delay(pwm_step_time);
    }
    old_pwm = new_pwm;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question