基本流程:
1.配置定时器
2.开启定时器
3.动态改变pwm输出,改变值
HAL_TIM_PWM_Start
(&
htim4
,
TIM_CHANNEL_1
);
函数总结
__HAL_TIM_SET_COMPARE() // 是设置CCRx,一般是用在PWM输出的,控制PWM占空比 __HAL_TIM_GET_COMPARE // 是用来读取CCRx的,一般用于捕获处理
PWM输出配置:
频率设置:
static void MX_TIM2_Init(void) { TIM_MasterConfigTypeDef sMasterConfig; TIM_IC_InitTypeDef sConfigIC; TIM_OC_InitTypeDef sConfigOC; htim2.Instance = TIM2; htim2.Init.Prescaler = (36-1); //实际时钟频率为 72M/36=2MHz /40000=50H,-----490HZ,改变观察电机输出状态 定时器预分频器 htim2.Init.CounterMode = TIM_COUNTERMODE_UP; htim2.Init.Period = (4082-1); //定时器周期配置 PWM频率为 490KHz 定义定时器周期,PWM频率为:168MHz/ (L298N_TIMx_PRESCALER+1)/ (L298N_TIM_PERIOD+1) htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; // 时钟分频 //高级定时器重复计数寄存器值 **高级才有 // 定义高级定时器重复计数寄存器值 //实际PWM频率为:72MHz/(L298N_TIMx_PRESCALER+1)/(L298N_TIM_PERIOD+1)/(L298N_TIM_REPETITIONCOUNTER+1) #define L298N_TIM_REPETITIONCOUNTER 0 **
刹车和死区配置
/* 刹车和死区时间配置 */ sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE; sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE; sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF; sBreakDeadTimeConfig.DeadTime = 0; sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE; sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_HIGH; sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE; HAL_TIMEx_ConfigBreakDeadTime(&htimx_L298N, &sBreakDeadTimeConfig);
基于通信的pwm频率和脉宽的更新控制算法
/* ** pwm是否需要更新,比较上一次的频率和脉宽值,如果不同,则更新 */ void pwm_update_loop( void ) { /*1,第一路判断: 频率 或 占空比发生变化 */ if( (HLM_SOKO_I_FREQ != HLM_SOKO_I_FREQ_LAST ) || HLM_SOKO_I_DUTY != HLM_SOKO_I_DUTY_LAST ) { /* 更新 频率和占空比的记录值 */ HLM_SOKO_I_FREQ_LAST = HLM_SOKO_I_FREQ; HLM_SOKO_I_DUTY_LAST = HLM_SOKO_I_DUTY; /* 更新当前通道的PWM波形 */ pwm_update( PWM_I,HLM_SOKO_I_FREQ, HLM_SOKO_I_DUTY ); } /*2,第二路判断 */ if( (HLM_SOKO_II_FREQ != HLM_SOKO_II_FREQ_LAST ) || HLM_SOKO_II_DUTY != HLM_SOKO_II_DUTY_LAST ) { /* 更新 频率和占空比的记录值 */ HLM_SOKO_II_FREQ_LAST = HLM_SOKO_II_FREQ; HLM_SOKO_II_DUTY_LAST = HLM_SOKO_II_DUTY; /* 更新当前通道的PWM波形 */ pwm_update( PWM_II,HLM_SOKO_II_FREQ, HLM_SOKO_II_DUTY ); } /*3,第三路判断 */ if( (HLM_SOKO_III_FREQ != HLM_SOKO_III_FREQ_LAST ) || HLM_SOKO_III_DUTY != HLM_SOKO_III_DUTY_LAST ) { /* 更新 频率和占空比的记录值 */ HLM_SOKO_III_FREQ_LAST = HLM_SOKO_III_FREQ; HLM_SOKO_III_DUTY_LAST = HLM_SOKO_III_DUTY; /* 更新当前通道的PWM波形 */ pwm_update( PWM_III,HLM_SOKO_III_FREQ, HLM_SOKO_III_DUTY ); } }