pwm.c
#include "pwm.h"
void pwm_init(void)
{
timer_parameter_struct timer_initpara;
timer_oc_parameter_struct timer_ocintpara;
//PC9配置为复用推挽输出
rcu_periph_clock_enable(RCU_GPIOC);
gpio_mode_set(GPIOC, GPIO_MODE_AF, GPIO_PUPD_NONE,GPIO_PIN_9);
gpio_output_options_set(GPIOC, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ,GPIO_PIN_9);
gpio_af_set(GPIOC, GPIO_AF_2, GPIO_PIN_9);
rcu_periph_clock_enable(RCU_TIMER2);
rcu_timer_clock_prescaler_config(RCU_TIMER_PSC_MUL4);
timer_struct_para_init(&timer_initpara);
timer_deinit(TIMER2);
/* TIMER2 configuration */
timer_initpara.prescaler = 119;
timer_initpara.alignedmode = TIMER_COUNTER_EDGE;
timer_initpara.counterdirection = TIMER_COUNTER_UP;
timer_initpara.period = 500;
timer_initpara.clockdivision = TIMER_CKDIV_DIV1;
timer_initpara.repetitioncounter = 0;
timer_init(TIMER2,&timer_initpara);
/* CH3 configuration in PWM mode 0 */
timer_channel_output_struct_para_init(&timer_ocintpara);
timer_ocintpara.ocpolarity = TIMER_OC_POLARITY_HIGH;
timer_ocintpara.outputstate = TIMER_CCX_ENABLE;
timer_ocintpara.ocnpolarity = TIMER_OCN_POLARITY_HIGH;
timer_ocintpara.outputnstate = TIMER_CCXN_DISABLE;
timer_ocintpara.ocidlestate = TIMER_OC_IDLE_STATE_LOW;
timer_ocintpara.ocnidlestate = TIMER_OCN_IDLE_STATE_LOW;
timer_channel_output_config(TIMER2,TIMER_CH_3,&timer_ocintpara);
/* CH3 configuration in PWM mode 0,duty cycle 25% */
timer_channel_output_pulse_value_config(TIMER2,TIMER_CH_3,0);
timer_channel_output_mode_config(TIMER2,TIMER_CH_3,TIMER_OC_MODE_PWM0);
timer_channel_output_shadow_config(TIMER2,TIMER_CH_3,TIMER_OC_SHADOW_DISABLE);
/* auto-reload preload enable */
timer_auto_reload_shadow_enable(TIMER2);
/* TIMER1 enable */
timer_enable(TIMER2);
}
pwm.h
#ifndef __PWM_H
#define __PWM_H
#include "head.h"
void pwm_init(void);
#endif
主函数
pwm_init();
while(1)
{
for(int i=0;i<500;i++)
{
timer_channel_output_pulse_value_config(TIMER2,TIMER_CH_3,i);
delay_1ms(1);
}
for(int i=500;i>0;i--)
{
timer_channel_output_pulse_value_config(TIMER2,TIMER_CH_3,i);
delay_1ms(1);
}
}