Timer - Twinkle0613/PCB-Laser-Etcher GitHub Wiki

Timer in Counter Mode

In PCB Laser Etcher project, the timer as scheduler was used to manage the time of every tasks in counter mode. Before applying in the project, I tried to write a simple program to test the function of TIM2 in stm32f103T8C6 board. I made the GPIOA pin 9 to generate a square wave continuously when once the counter reached 640 ticks that was set in CNT register. The code was shown as the bottom code block.

/**
 * Timer in Counter Mode
 *
 * When Once the counter reached 640 tick, the GPIOA pin 9 
 * will change the state for generating a square wave.
 *
 */


#include <stdint.h>
#include "Timer_setting.h"
#include "stm32f10x_tim.h"
#include "stm32f10x_rcc.h"

int main(void)
{
    int k = 1;
    /* Enable Clock for GPIOA*/
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
    /* Disable Clock Reset for GPIOA*/
    RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOA,DISABLE);
    /* Enable Clock for TIM2*/
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2 ,ENABLE);
    /* Disable Clock Reset for TIM2*/
    RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM2 ,DISABLE);
    /* Configure GPIOA
       gpio.GPIO_Pin = GPIO_Pin_9;
       gpio.GPIO_Speed = GPIO_Speed_50MHz;
       gpio.GPIO_Mode = GPIO_Mode_Out_PP;
    */
    GPIO_conf(GPIOA,GPIO_Pin_9,GPIO_Speed_50MHz,GPIO_Mode_Out_PP);   
    /* Configure TIM2
      timer.TIM_Prescaler = 4;
      timer.TIM_CounterMode = TIM_CounterMode_Up;
      timer.TIM_Period = 640;
      timer.TIM_ClockDivision = TIM_CKD_DIV1;  
    */
    Timer_conf(TIM2,4,TIM_CounterMode_Up,640,TIM_CKD_DIV1);
    /* Enable TIM2*/
    enableTimer(TIM2,ENABLE);
    while(1)
    {

    	if(TIM_GetFlagStatus(TIM2, TIM_FLAG_Update) == SET) {
            if(k++ & 0x1){
          	  GPIO_SetBits(GPIOA, GPIO_Pin_9); // Output High
            }else{
          	  GPIO_ResetBits(GPIOA, GPIO_Pin_9); // Output Low 
            }
    		TIM_ClearFlag(TIM2, TIM_FLAG_Update); // Clear the Update flag
    	}
    }
}

Timer_Conf() function was created to make the user more easy to configure the timer. The function was shown in bottom code block. The code can get from Timer_setting.c in PCB Laser Ecther project

void Timer_conf(TIM_TypeDef* TIMx,
                uint16_t Prescaler,
                uint16_t CounterMode,
                uint16_t Period,
                uint16_t ClockDivision
              ){
                
  TIM_TimeBaseInitTypeDef timer;
  
  timer.TIM_Prescaler = Prescaler;
  timer.TIM_CounterMode = CounterMode;
  timer.TIM_Period = Period;
  timer.TIM_ClockDivision = ClockDivision;  

  TIM_TimeBaseInit(TIMx,&timer);
}

This function included some of the function from the Standard Library of STM32F103.

enableTimer() function was create to enable the timer. you may refer timer_setting.c in PCB Laser Etcher project.

GPIO_conf() function can be refer to GPIO_setting.c in PCB Laser Etcher project.

⚠️ **GitHub.com Fallback** ⚠️