ST方案一个MCU带动两个无刷电机驱动的原生逻辑

发布时间 2023-09-30 18:05:13作者: smilingfrog
TIM1 TIM8两个高级定时器,设置TIM2为启动计数触发源,触发时钟同步,并且设置上,两者错开相。核心思路是错开电流采样和处理的时刻
 1   /* disable main TIM counter to ensure
 2    * a synchronous start by TIM2 trigger */
 3   LL_TIM_DisableCounter( TIMx );
 4   
 5   LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET);
 6 
 7   /* Enables the TIMx Preload on CC1 Register */
 8   LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 );
 9   /* Enables the TIMx Preload on CC2 Register */
10   LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 );
11   /* Enables the TIMx Preload on CC3 Register */
12   LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 );
13   /* Enables the TIMx Preload on CC4 Register */
14   LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH4 );
15 //这里是关键,让TIM1和TIM8产生一个相差
16   /* Prepare timer for synchronization */
17   LL_TIM_GenerateEvent_UPDATE( TIMx );
18   if ( pHandle->pParams_str->FreqRatio == 2u )//两个高级定时器频率关系是两倍
19   {
20     if ( pHandle->pParams_str->IsHigherFreqTim == HIGHER_FREQ )//当前定时器是更高频率
21     {
22       if ( pHandle->pParams_str->RepetitionCounter == 3u )//RepetitionCounter等于3表示每两个完整PWM周期执行一次电流采样,恰好等于低频定时器的频率,需要错开,这样高频的触发点永远在低频的下降沿
23       {
24         /* Set TIMx repetition counter to 1 */
25         LL_TIM_SetRepetitionCounter( TIMx, 1 );
26         LL_TIM_GenerateEvent_UPDATE( TIMx );
27         /* Repetition counter will be set to 3 at next Update */
28         LL_TIM_SetRepetitionCounter( TIMx, 3 );
29       }
30     }
31     LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u );
32   }
33   else /* bFreqRatio equal to 1 or 3 *///两个高级定时器频率关系相同或者3倍
34   {
35     if ( pHandle->_Super.Motor == M1 )
36     {
37       if ( pHandle->pParams_str->RepetitionCounter == 3u )//RepetitionCounter等于3表示每两个完整PWM周期执行一次电流采样,错开是为了时间上更均分
38       {
39         /* Set TIMx repetition counter to 1 */
40         LL_TIM_SetRepetitionCounter( TIMx, 1 );
41         LL_TIM_GenerateEvent_UPDATE( TIMx );
42         /* Repetition counter will be set to 3 at next Update */
43         LL_TIM_SetRepetitionCounter( TIMx, 3 );
44       }
45       LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u );//必须(高频的)强制移相,把两个定时器上升沿错开
46 
47     }
48     else
49     {
50     }
51   }
以上的写法并不是完备的,实际处理时还要注意。