#include "gd32f10x.h" // Device header
void PWM_Init(void)
{
//输出比较与定时器初始化结构体 刹车结构体
timer_oc_parameter_struct timer_ocintpara;
timer_parameter_struct timer_initpara;
timer_break_parameter_struct timer_breakpara;
//时钟 TIMER0 GPIOA GPIOB
rcu_periph_clock_enable(RCU_TIMER0);
rcu_periph_clock_enable(RCU_GPIOA);
rcu_periph_clock_enable(RCU_GPIOB);
rcu_periph_clock_enable(RCU_AF);
//PA1初始化 复用推挽输出
gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_8);
//PB13 互补通道初始化 复用推挽输出
gpio_init(GPIOB, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_13);
/* configure PB12(TIMER0 BKIN) as alternate function */
gpio_init(GPIOB, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_12);
timer_deinit(TIMER0);
/* TIMER0 参数配置 */
timer_initpara.prescaler = 108 - 1; //PSC
timer_initpara.alignedmode = TIMER_COUNTER_EDGE;
timer_initpara.counterdirection = TIMER_COUNTER_UP;
timer_initpara.period = 600 - 1; //ARR
timer_initpara.clockdivision = TIMER_CKDIV_DIV1;
timer_initpara.repetitioncounter = 0;
timer_init(TIMER0,&timer_initpara);
//输出比较参数配置
timer_ocintpara.outputstate = TIMER_CCX_ENABLE;//输出使能
timer_ocintpara.outputnstate = TIMER_CCXN_ENABLE;//互补输出使能
timer_ocintpara.ocpolarity = TIMER_OC_POLARITY_HIGH;//高极性,不反转,REF直接输出
timer_ocintpara.ocnpolarity = TIMER_OCN_POLARITY_HIGH;
timer_ocintpara.ocidlestate = TIMER_OC_IDLE_STATE_HIGH;
timer_ocintpara.ocnidlestate = TIMER_OCN_IDLE_STATE_HIGH;
//通道选择
timer_channel_output_config(TIMER0,TIMER_CH_0,&timer_ocintpara);
/* CH0 configuration in PWM mode1,duty cycle 0% */
timer_channel_output_pulse_value_config(TIMER0,TIMER_CH_0,0);//CCR 占空比
timer_channel_output_mode_config(TIMER0,TIMER_CH_0,TIMER_OC_MODE_PWM0);//PWM模式0 模式1
timer_channel_output_shadow_config(TIMER0,TIMER_CH_0,TIMER_OC_SHADOW_ENABLE);
/* automatic output enable, break, dead time and lock configuration*/
timer_breakpara.runoffstate = TIMER_ROS_STATE_ENABLE;
timer_breakpara.ideloffstate = TIMER_IOS_STATE_ENABLE ;
timer_breakpara.deadtime = 164;
timer_breakpara.breakpolarity = TIMER_BREAK_POLARITY_LOW;
timer_breakpara.outputautostate = TIMER_OUTAUTO_ENABLE;
timer_breakpara.protectmode = TIMER_CCHP_PROT_OFF;
timer_breakpara.breakstate = TIMER_BREAK_ENABLE;
timer_break_config(TIMER0,&timer_breakpara);
/* auto-reload preload enable */
// timer_auto_reload_shadow_enable(TIMER0);
/* TIMER0 primary output function enable */
timer_primary_output_config(TIMER0,ENABLE);
/* TIMER0 channel control update interrupt enable */
timer_interrupt_enable(TIMER0,TIMER_INT_CMT);
/* TIMER0 break interrupt disable */
timer_interrupt_disable(TIMER0,TIMER_INT_BRK);
nvic_priority_group_set(NVIC_PRIGROUP_PRE1_SUB3);
nvic_irq_enable(TIMER0_TRG_CMT_IRQn, 0, 1);
/* TIMER0 counter enable */
timer_enable(TIMER0);
}
void PWM_SetCompare1(uint16_t Compare)
{
timer_channel_output_pulse_value_config(TIMER0,TIMER_CH_0,Compare);
} |