1、使用引脚PA7
可以选择定时器2的通道1,也可以选择定时器13的通道0
2、变量定义
#define PID_GPIO_RCU RCU_GPIOA
#define PID_GPIO_PERIPH GPIOA
#define PID_GPIO_PIN GPIO_PIN_7
#define PID_ALT_NUM GPIO_AF_2 // 复用
#define PID_TIMER_RCU RCU_TIMER2 // 复用
#define PID_TIMER TIMER2 // 使用的定时器
#define PID_TIMER_CH TIMER_CH_1 // 使用的定时器通道
3、定时器初始化
/* 定时器初始化
* 时钟频率:240Mhz ==> main 中 rcu_timer_clock_prescaler_config(RCU_TIMER_PSC_MUL4);
* 预分频 :24000 ==> 频率为:240MHZ/24000 = 10kHZ
* PWM频率 :装载值 = 10000 ==> 10kHZ /10000 = 1HZ ==> 1个周期为 1/1Hz = 1s
*/
const uint16_t g_prescaler = 24000-1; // 预分频系数 24000-1
const uint16_t g_period = 10000-1; // 装载值 10000-1
void PID_Timer_Init()
{
timer_parameter_struct timer1_init;
timer_struct_para_init(&timer1_init); //将定时器结构体内参数配置成默认参数
rcu_periph_clock_enable(PID_TIMER_RCU); // 使能定时器的时钟
timer_deinit(PID_TIMER);
/* TIMER1 configuration */
timer1_init.prescaler = g_prescaler; // 预分频系数
timer1_init.period = g_period; // 自动重装载值, 周期
timer1_init.alignedmode = TIMER_COUNTER_EDGE; // 配置为边沿对其模式
timer1_init.counterdirection = TIMER_COUNTER_UP; // 配置计数方向为向上计数
timer1_init.clockdivision = TIMER_CKDIV_DIV1; // 配置死区时间和采样时钟(DTS)之间的分频系数
timer1_init.repetitioncounter = 0; // 设置重复计数器值,0表示不重复计数,每次溢出都产生更新事件
timer_init(PID_TIMER,&timer1_init);
/* CH1 configuration in PWM mode */
timer_oc_parameter_struct timer_ocintpara;
timer_ocintpara.outputstate = TIMER_CCX_ENABLE; // 使能通道输出
timer_ocintpara.outputnstate = TIMER_CCXN_DISABLE; // 禁用互补通道输出
timer_ocintpara.ocpolarity = TIMER_OC_POLARITY_HIGH; // 通道输出极性
timer_ocintpara.ocnpolarity = TIMER_OCN_POLARITY_HIGH; // 互补通道输出极性
timer_ocintpara.ocidlestate = TIMER_OC_IDLE_STATE_LOW; // 空闲时通道输出极性
timer_ocintpara.ocnidlestate = TIMER_OCN_IDLE_STATE_LOW; // 空闲时互补通道输出极性
timer_channel_output_config(PID_TIMER, PID_TIMER_CH, &timer_ocintpara);
timer_channel_output_pulse_value_config(PID_TIMER, PID_TIMER_CH, 0);
timer_channel_output_mode_config (PID_TIMER, PID_TIMER_CH, TIMER_OC_MODE_PWM0); //配置通道输出模式
timer_channel_output_shadow_config (PID_TIMER, PID_TIMER_CH, TIMER_OC_SHADOW_DISABLE);
timer_primary_output_config (PID_TIMER, ENABLE);
timer_auto_reload_shadow_enable (PID_TIMER);//使能自动重加载
timer_enable(PID_TIMER);
}
定时器的时钟频率要使用以下函数先进行设置,设置4倍频可以让所有定时器时钟频率都达到240MHZ
// 设置定时器时钟频率:60 * 4 = 240MHZ
rcu_timer_clock_prescaler_config(RCU_TIMER_PSC_MUL4);
4、设置占空比
//设置占空比
void PID_Set_PWM(float pulse)
{
timer_channel_output_pulse_value_config(PID_TIMER, PID_TIMER_CH, g_period*pulse);
}
5、模块初始化,设置初始占空比为50%
/* 模块初始化 */
void PID_Init(void)
{
// 加热器 PA0 --> 定时器 TIMER1_CH0
rcu_periph_clock_enable(PID_GPIO_RCU); /* 使能 GPIOA的时钟 */
gpio_af_set (PID_GPIO_PERIPH, PID_ALT_NUM, PID_GPIO_PIN);
gpio_mode_set (PID_GPIO_PERIPH, GPIO_MODE_AF, GPIO_PUPD_NONE, PID_GPIO_PIN);
gpio_output_options_set(PID_GPIO_PERIPH, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, PID_GPIO_PIN);
gpio_bit_set (PID_GPIO_PERIPH, PID_GPIO_PIN);
PID_Timer_Init();
PID_Set_PWM(0.5);
}
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/lucky_sunshine/article/details/134810991
|