How to change pwm period on runtime in ncs?

Hi, 

I'm trying to play some sounds on a piezo with the help of the pwm. I tried to set the period with pwm_set_dt but only the first call is successful and every subsequent call raised an error. 

Here is my test code:

    for(uint16_t i = 400; i < 800; i++)
    {
        int ret = pwm_set_dt(&piezo_pwm_pos, PWM_HZ(i),
						   PWM_HZ(i) / 2);
        LOG_DBG("pwm_set_dt = %d", ret);

        ret = pwm_set_dt(&piezo_pwm_neg, PWM_HZ(i),
						   PWM_HZ(i) / 2);
        LOG_DBG("pwm_set_dt = %d", ret);
        k_msleep(10);
    }

The results looked like this:

00> D: pwm_set_dt = 0
00> D: pwm_set_dt = 0
00> E: Incompatible period.
00> D: pwm_set_dt = -22
00> E: Incompatible period.
00> D: pwm_set_dt = -22
00> E: Incompatible period.
00> D: pwm_set_dt = -22
00> E: Incompatible period.
00> D: pwm_set_dt = -22
00> E: Incompatible period.
00> D: pwm_set_dt = -22

I didn't find anything in the documentation of pwm_set for the error 22.

How can I change period and pulse while the pwm is running?

Best regards,

Christian

Parents Reply
  • Try using the  pwm_set_cycles() function. And use PWM_POLARITY_NORMAL on one channel, and  
    PWM_POLARITY_INVERTED on the other. Snippet:
    ret = pwm_set_cycles(pwm_led0->dev, pwm_led0->channel, period_cycles, period_cycles / 2,
    	PWM_POLARITY_INVERTED);
    
    ret = pwm_set_cycles(pwm_led1->dev, pwm_led1->channel, period_cycles, period_cycles / 2,
    		PWM_POLARITY_NORMAL);
Children
Related