2018年4月11日 星期三

Nordic nRF52832 PWM Library介紹

#include "nrf.h"
#include "app_error.h"
#include "bsp.h"
#include "app_pwm.h"
#include "nrf_delay.h"

APP_PWM_INSTANCE(PWM0,0); // Create the instance "PWM0" using TIMER0.
void pwm_ready_callback(uint32_t pwm_id)    // PWM callback function
{
    ready_flag = true;
}
int main(void)
{
 ret_code_t err_code;
 
 /* 2-channel PWM, 1000Hz, output on p0.17 & p0.18 */
        app_pwm_config_t pwm0_cfg = APP_PWM_DEFAULT_CONFIG_2CH(1000L, 17, 18);
 
 /* Switch the polarity of the second channel. */
 pwm0_cfg.pin_polarity[0] = APP_PWM_POLARITY_ACTIVE_HIGH;
 pwm0_cfg.pin_polarity[1] = APP_PWM_POLARITY_ACTIVE_LOW;
 
 app_pwm_init(&PWM0,&pwm0_cfg,pwm_ready_callback);
 app_pwm_enable(&PWM0);
 
 ready_flag = false;
 while (app_pwm_channel_duty_set(&PWM0, 0, 0) == NRF_ERROR_BUSY);
 while (!ready_flag);
 ready_flag = false;
 while (app_pwm_channel_duty_set(&PWM0, 1, 0) == NRF_ERROR_BUSY);
 while (!ready_flag);
 
 uint32_t value;
        while (true)
        {
            for (uint8_t i = 0; i < 40; ++i)
            {
            value = (i < 20) ? (i * 5) : (100 - (i - 20) * 5);

            ready_flag = false;
            // Set the duty cycle - keep trying until PWM is ready... 
            while (app_pwm_channel_duty_set(&PWM0, 0, value) == NRF_ERROR_BUSY);

            // ... or wait for callback. 
            while (!ready_flag);
            APP_ERROR_CHECK(app_pwm_channel_duty_set(&PWM0, 1, value));
            nrf_delay_ms(25);
            }
        }
}
函式APP_PWM_INSTANCE(PWM0,0) ;是指PWM0模組時序是TIMER0。
函式APP_PWM_DEFAULT_CONFIG_2CH(1000L, 17, 18);PWM模組有兩個頻道輸出,為channel0為P0.17,channel1為P0.18,頻率為1000Hz。
pwm0_cfg.pin_polarity[0] = APP_PWM_POLARITY_ACTIVE_HIGH;
channel0 的PWM POLARITY為High。
pwm0_cfg.pin_polarity[1] = APP_PWM_POLARITY_ACTIVE_LOW;
channel1 的PWM POLARITY為Low。
函式app_pwm_init(&PWM0,&pwm0_cfg,pwm_ready_callback);PWM0初時化設定及設定callback函式。
函式app_pwm_enable(&PWM0);啟動PWM0
函式app_pwm_channel_duty_set(&PWM0, 0, value);channel0 pwm duty設定,value為0~100。

沒有留言:

張貼留言