Electronic – STM32F051R8: PWM timers don’t work

gpiopwmstm32stm32f0timer

I'm working with MB1034B discovery board and STM32F051R8 microprocessor. I'm trying to output some PWM pulses using hardware timers. I use this tutorial (for STM32F4xx): http://visualgdb.com/tutorials/arm/stm32/pwm/

The problem is, that after some changes needed to compile the code, which I have no idea if are correct, it doesn't work. I'm using VisualGDB and VS2013 Community. I have a led on PC8 and PC9.

Thanks for your help. Here's my code:

#include <stm32f0xx_gpio.h>
#include <stm32f0xx_rcc.h>
#include <stm32f0xx_tim.h>

void InitializeTimer(int period = 500)
{
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

    TIM_TimeBaseInitTypeDef timerInitStructure;
    timerInitStructure.TIM_Prescaler = 40000;
    timerInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
    timerInitStructure.TIM_Period = period;
    timerInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    timerInitStructure.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM2, &timerInitStructure);
    TIM_Cmd(TIM2, ENABLE);
}

void InitializePWMChannel()
{
    TIM_OCInitTypeDef outputChannelInit = { 0, };
    outputChannelInit.TIM_OCMode = TIM_OCMode_PWM1;
    outputChannelInit.TIM_Pulse = 400;
    outputChannelInit.TIM_OutputState = TIM_OutputState_Enable;
    outputChannelInit.TIM_OCPolarity = TIM_OCPolarity_High;

    TIM_OC2Init(TIM2, &outputChannelInit);
    TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Enable);

    GPIO_PinAFConfig(GPIOC, GPIO_PinSource9, GPIO_AF_2);
}

void InitializeLEDs()
{
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOC, ENABLE);

    GPIO_InitTypeDef gpioStructure;
    gpioStructure.GPIO_Pin = GPIO_Pin_9;
    gpioStructure.GPIO_Mode = GPIO_Mode_AF;
    gpioStructure.GPIO_OType = GPIO_OType_PP;
    gpioStructure.GPIO_PuPd = GPIO_PuPd_UP;
    gpioStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOC, &gpioStructure);
}


int main()
{
    InitializeLEDs();
    InitializeTimer();
    InitializePWMChannel();

    for (;;)
    {
    }
}

Best Answer

In your part the port C pins 8 and 9 have an alternate functions as a Timer3 channel, but you are trying to use them with Timer2, which will not work of course. See the page 34 in the datasheet. In addition, I don't see anything related to PC8 in the code, but you are saying it has a LED connected to it.

Related Topic