GD32F4定时器之单通道输出PWM

使用Timer4的CH1输出占空比50%,频率800KHz的PWM波形

 4 void TimerConfig(void)
 5 {
 6     timer_deinit(TIMER4);
 7     rcu_periph_clock_enable(RCU_GPIOA);
 8     rcu_periph_clock_enable(RCU_GPIOC);
 9     rcu_periph_clock_enable(RCU_TIMER4);
10 
11     timer_internal_clock_config(TIMER4);    //选择内部时钟CK_TIMER(200M)
12 16 
17     gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_1);
18     gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_1);
19     gpio_af_set(GPIOA, GPIO_AF_2, GPIO_PIN_1);
20 
21     /* TIMER1配置为0.1ms定时 */
22     timer_parameter_struct timer_initpara;
23 
24     timer_initpara.prescaler         = 4;
25     timer_initpara.clockdivision     = TIMER_CKDIV_DIV1;//根据prescaler,clockdivision最终该定时器时钟评率为1M
26     timer_initpara.alignedmode       = TIMER_COUNTER_EDGE;//触发方式设置根据边沿决定
27     timer_initpara.counterdirection  = TIMER_COUNTER_UP;//设置为上升沿触发
28     timer_initpara.period            = 49;//设置为0.1ms触发一次
29     timer_initpara.repetitioncounter = 0;
30     timer_init(TIMER4, &timer_initpara);
31     
32     /* TIMER的CH1配置为PWM输出:边触发,这样保证每0.1ms产生一次触发 */
33     timer_oc_parameter_struct timer_ocintpara;
34     
35     timer_ocintpara.ocpolarity  = TIMER_OC_POLARITY_HIGH;
36     timer_ocintpara.outputstate = TIMER_CCX_ENABLE;
37     timer_ocintpara.ocnpolarity  = TIMER_OCN_POLARITY_HIGH;
38     timer_ocintpara.outputnstate = TIMER_CCXN_DISABLE;
39     timer_ocintpara.ocidlestate  = TIMER_OC_IDLE_STATE_LOW;
40     timer_ocintpara.ocnidlestate = TIMER_OCN_IDLE_STATE_LOW;
41     timer_channel_output_config(TIMER4,TIMER_CH_1,&timer_ocintpara);
42     
43     timer_channel_output_pulse_value_config(TIMER4, TIMER_CH_1, 25);
44     timer_channel_output_mode_config(TIMER4, TIMER_CH_1, TIMER_OC_MODE_PWM0);
45     timer_channel_output_shadow_config(TIMER4, TIMER_CH_1, TIMER_OC_SHADOW_DISABLE);
46 
47     /* 使能TIMERx_CAR寄存器的影子寄存器 */
48     timer_auto_reload_shadow_enable(TIMER4);
49     /* 所有通道输出使能 */
50     timer_primary_output_config(TIMER4, ENABLE);
51 
52     timer_enable(TIMER4);
53 
54     timer_interrupt_enable(TIMER4,TIMER_INT_UP);    
55 
56     return;
57 }

测量PA1,即可看到800KHz的PWM波形

上一篇:openwrt 实现对shell脚本的守护处理


下一篇:【STM32】PWM驱动舵机(TIM3CH2)