Electrical – Using Tim2 (84MHz) to blink Led for every 500ms – STM32F407VG

ledstm32f4timer

I developped a code in ordrer to blink a Led every 500ms using the timer 2 with a frequency of 84Mhz.

I generate the file "system_stm32f4xx.c" to have a frequency of 84MHz for Tim2.

enter image description here

I modified the file "stm32f4xx.h" by adding the line

#define HSE_VALUE ((uint32_t)8000000)

I modified the file "startup_stm32f4xx.c" by uncommenting the function SystemInit() and adding it before the main() in the function Default_Reset_Handler().

After that I created the project show below.

The problem is that I do not get the excepted result, The led blink every 100ms :

#include "stm32f4xx.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_tim.h"

void InitializeLEDs()
{
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
GPIO_InitTypeDef gpioStructure;
gpioStructure.GPIO_Pin = GPIO_Pin_12 ;
gpioStructure.GPIO_Mode = GPIO_Mode_OUT;
gpioStructure.GPIO_OType = GPIO_OType_PP;
gpioStructure.GPIO_Speed = GPIO_Speed_50MHz;
gpioStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOD, &gpioStructure);
}

void InitializeTimer()
{
// Ftim2 = 84Mhz
TIM_TimeBaseInitTypeDef timerInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
timerInitStructure.TIM_Prescaler = 84000 - 1; // counter rate is 1ms
timerInitStructure.TIM_Period = 60000;
timerInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
timerInitStructure.TIM_ClockDivision = 0;
timerInitStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &timerInitStructure);
}

void delay_ms(uint16_t ms)
{
TIM_SetCounter(TIM2, 0);    // Make sure TIM2 Counter start from zero
TIM_Cmd(TIM2, ENABLE);              // Enalbe TIM2
while(TIM_GetCounter(TIM2) < ms);   // Wait ms Miliseconds
TIM_Cmd(TIM2, DISABLE);
}

int main(void)
{
InitializeLEDs();
InitializeTimer();
    while(1)
    {
        GPIO_SetBits(GPIOD, GPIO_Pin_12);
        delay_ms(500);
        GPIO_ResetBits(GPIOD, GPIO_Pin_12);
        delay_ms(500);
    }
}

Here is the result :

enter image description here

Best Answer

You want to learn how to use those automatically generated code. Modifying them requires really good understanding of how it works.

As to your code, read the manual on how those functions work, in conjunction with the datasheet. Pay particular attention which variable is 16 bit or 32 bit so that your values given to those functions don't overflow.

Lastly write your code so that it does what you want to do. For example to produce a 0 5s delay on a 84mhz clock needs 42million cycles, to be broken down between the prescaler and the reload register. You can figure out what the right values should be.

It is sufficient to say that what you have aren't right.