简体   繁体   中英

STM32F103 TIM1 pwm output

I suppose I'm doing something wrong when initializing the PWM of TIM1. I need to get a signal on PA8, but my code (which works fine for TIM2-TIM5) does not work for TIM1. Are any of the settings wrong below?

First I was thinking that it was because I was not calling TIM_OCStructInit(), but after adding it I still get a low level on PA8 and no signal. It is configured as AF_PP, and I'm not remapping TIM1..

... {.tim = TIM1, .id = RCC_APB2Periph_TIM1, 
    .channels = {
        {.gpio = GPIOA, .gpio_pin = GPIO_Pin_8, },
        {.gpio = GPIOA, .gpio_pin = GPIO_Pin_9, },
        {.gpio = GPIOA, .gpio_pin = GPIO_Pin_10, },
        {.gpio = GPIOA, .gpio_pin = GPIO_Pin_11, }
    }
} ... 

.....

RCC_APB1PeriphClockCmd(_timers[tim_id].id, ENABLE);

TIM_TimeBaseInitTypeDef timerInitStructure;
TIM_OCInitTypeDef outputChannelInit;

TIM_TimeBaseStructInit(&timerInitStructure); 

timerInitStructure.TIM_Prescaler = F_CPU/1000000UL; // set 1us resolution
timerInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
timerInitStructure.TIM_Period = period;
timerInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
timerInitStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIMx, &timerInitStructure);

TIM_OCStructInit(&outputChannelInit); 

outputChannelInit.TIM_OCMode = TIM_OCMode_PWM1;
outputChannelInit.TIM_Pulse = def_width;
outputChannelInit.TIM_OutputState = TIM_OutputState_Enable;
outputChannelInit.TIM_OCPolarity = TIM_OCPolarity_High;


switch((chan & 0x3)){
    case 0: 
        TIM_OC1Init(TIMx, &outputChannelInit);
        TIM_OC1PreloadConfig(TIMx, TIM_OCPreload_Enable);
        break; 
    case 1: 
        TIM_OC2Init(TIMx, &outputChannelInit);
        TIM_OC2PreloadConfig(TIMx, TIM_OCPreload_Enable);
        break; 
    case 2: 
        TIM_OC3Init(TIMx, &outputChannelInit);
        TIM_OC3PreloadConfig(TIMx, TIM_OCPreload_Enable);
        break; 
    case 3: 
        TIM_OC4Init(TIMx, &outputChannelInit);
        TIM_OC4PreloadConfig(TIMx, TIM_OCPreload_Enable);
        break; 
}; 

//TIM_ARRPreloadConfig(TIMx, ENABLE);
TIM_CtrlPWMOutputs(TIMx, ENABLE);
TIM_Cmd(TIMx, ENABLE);

GPIO_InitTypeDef gpioStructure;
gpioStructure.GPIO_Pin = _timers[tim_id].channels[chan & 0x3].gpio_pin;
gpioStructure.GPIO_Mode = GPIO_Mode_AF_PP;
gpioStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(_timers[tim_id].channels[chan & 0x3].gpio, &gpioStructure);

Got it! I was using RCC_APB1PeriphClockCmd for all timers when I should have used RCC_APB2PeriphClockCmd for TIM1. Now everything works great!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM