On this example we configure two complementary PWM channels ( when one channel is in high polarity the complement is in low ) with dead time insertion. This configuration is really useful to control single phase driver motors in H bridge mode. It is necessary to call HAL_TIMEx_PWMN_Start
function to generate the complementary signal.
#include "bsp.h"
TIM_HandleTypeDef TimHandle; /*TIM control structure*/
TIM_OC_InitTypeDef sConfig; /*PWM channel structure*/
/*dead time config structure*/
TIM_BreakDeadTimeConfigTypeDef sBrkConfig;
int main( void )
{
HAL_Init(); /*Init library*/
/* Config TIM1 to generate a signal with a 2KHz period*/
TimHandle.Instance = TIM1;
TimHandle.Init.Prescaler = 10;
TimHandle.Init.Period = 800;
TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_PWM_Init( &TimHandle );
/* Config PWM channel with high polarity at 50% duty cycle */
sConfig.OCMode = TIM_OCMODE_PWM1;
sConfig.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfig.OCNPolarity = TIM_OCNPOLARITY_HIGH;
HAL_TIM_PWM_ConfigChannel( &TimHandle, &sConfig, TIM_CHANNEL_1 );
/* Enable dead times to avoid conflicts when polarity changes */
sBrkConfig.BreakState = TIM_BREAK_DISABLE;
sBrkConfig.DeadTime = 200;
HAL_TIMEx_ConfigBreakDeadTime( &TimHandle, &sBrkConfig );
/* start the complementary signals */
HAL_TIM_PWM_Start( &TimHandle, TIM_CHANNEL_1 );
HAL_TIMEx_PWMN_Start( &TimHandle, TIM_CHANNEL_1 );
while (1)
{
}
}
msps.c
/*function called by HAL_TIM_PWM_Init to configure the slected pins as PWM outputs*/
void HAL_TIM_PWM_MspInit( TIM_HandleTypeDef *htim )
{
GPIO_InitTypeDef GPIO_InitStruct;
__TIM1_CLK_ENABLE(); /*eneable clock in TIM1*/
__GPIOA_CLK_ENABLE(); /*eneable clock on port A*/
/* pin A7 like TIM1_CH1N, A8 like TIM1_CH1 */
GPIO_InitStruct.Pin = GPIO_PIN_7 | GPIO_PIN_8;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF1_TIM1;
HAL_GPIO_Init( GPIOA, &GPIO_InitStruct );
}