准备工作
拿到板子以后,LED闪烁正常,说明板子正常。
由于以前用的MDK开发环境,本次想要改用IAR的环境,此处需要添加支持包,首先要把这个后缀名改为exe
另外,必须以管理员身份运行,能正确识别到本机IAR的安装路径
这样才能正确编译
Timer 基础
PWM 产生
如上图所示:ARR为溢出值(即下文的top),CCRx为比较值(即下文的xx),当该通道到达比较值和溢出值的时候就会反转输出的电平,以此来形成方波。
通过改变Top的大小来控制输出的频率,通过改变比较值可以调整方波有效电平的占比,设置输出电平极性,配置输出的有效电平。
top值设置说明:
1.现根据输出的频率确定一个最大的溢出值
2.根据通道的精度确定一个最小的溢出值,该值必须大于精度值。
由上可以得到在应用的时候,输出的频率和精度不能同时达到很高的水平,这受限于Timer的时钟频率。
代码段
初始化GPIO
gpio_mode_set(GPIOC, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN_6);
gpio_output_options_set(GPIOC, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_6);
gpio_af_set(GPIOC, GPIO_AF_3, GPIO_PIN_6);
如上图,注意选项GPIO复用功能
初始化Timer
void app_timer_init(void)
{
uint32_t timer_periph=TIMER7;
timer_oc_parameter_struct timer_ocintpara;
timer_parameter_struct timer_initpara;
rcu_periph_clock_enable(RCU_TIMER7);
rcu_timer_clock_prescaler_config(RCU_TIMER_PSC_MUL4);
timer_deinit(timer_periph);
timer_initpara.prescaler = 199;
timer_initpara.alignedmode = TIMER_COUNTER_EDGE;
timer_initpara.counterdirection = TIMER_COUNTER_UP;
timer_initpara.period = 15999;
timer_initpara.clockdivision = TIMER_CKDIV_DIV1;
timer_initpara.repetitioncounter = 0;
timer_init(timer_periph,&timer_initpara);
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(timer_periph,TIMER_CH_0,&timer_ocintpara);
timer_channel_output_pulse_value_config(timer_periph,TIMER_CH_0,15999);
timer_channel_output_mode_config(timer_periph,TIMER_CH_0,TIMER_OC_MODE_PWM0);
timer_channel_output_shadow_config(timer_periph,TIMER_CH_0,TIMER_OC_SHADOW_DISABLE);
// / * CH2 configuration in PWM mode1,duty cycle 50% * /
// timer_channel_output_pulse_value_config(timer_periph,TIMER_CH_2,7999);
// timer_channel_output_mode_config(timer_periph,TIMER_CH_2,TIMER_OC_MODE_PWM0);
// timer_channel_output_shadow_config(timer_periph,TIMER_CH_2,TIMER_OC_SHADOW_DISABLE);
//
// / * CH3 configuration in PWM mode1,duty cycle 75% * /
// timer_channel_output_pulse_value_config(timer_periph,TIMER_CH_3,11999);
// timer_channel_output_mode_config(timer_periph,TIMER_CH_3,TIMER_OC_MODE_PWM0);
// timer_channel_output_shadow_config(timer_periph,TIMER_CH_3,TIMER_OC_SHADOW_DISABLE);
timer_auto_reload_shadow_enable(timer_periph);
timer_enable(timer_periph);
}
如上配置后,定期改变
timer_channel_output_pulse_value_config(timer_periph,TIMER_CH_0,15999);的输出值,实现呼吸效果。
原作者:烟花易冷