cancel
Showing results for 
Search instead for 
Did you mean: 

TIM2 module not ticking at 1us in STM8S103F3 controller

RT T.1
Associate

I created a program on STM8S103F3 to generate a delay in rage of micro seconds using TIM2 module, but the timer is not ticking as expected and when I tried to call 1 sec delay using it, it is giving around 10 sec delay. I'm using 16MHz HSI oscillator and timer pre-scalar is set to 16. please see my code below. Please help me to figure out what is wrong with my code.

main()

{

   

  GPIO_Init(FAN_PORT , FAN_PIN, GPIO_MODE_OUT_OD_LOW_SLOW ); // Need to change mode to push pull

GPIO_WriteLow(FAN_PORT , FAN_PIN);

Serial_begin(9600); //Initialize Serial communication at 9600 baud rate

Serial_print_string("\r\n>>>>>>>>>>>>>>>>Board Up and Ready<<<<<<<<<<<<<<<<<\r\n"); //print a string

while (1){

    GPIO_WriteHigh(FAN_PORT , FAN_PIN);

    delay_ms(1000);

    GPIO_WriteLow(FAN_PORT , FAN_PIN);

    delay_ms(1000);

}

}

void clock_setup(void)

{

    CLK_DeInit();

    CLK_HSECmd(DISABLE);

    CLK_LSICmd(DISABLE);

    CLK_HSICmd(ENABLE);

    while(CLK_GetFlagStatus(CLK_FLAG_HSIRDY) == FALSE);

    CLK_ClockSwitchCmd(ENABLE);

    CLK_HSIPrescalerConfig(CLK_PRESCALER_HSIDIV1);

    CLK_SYSCLKConfig(CLK_PRESCALER_CPUDIV1);

    CLK_ClockSwitchConfig(CLK_SWITCHMODE_AUTO, CLK_SOURCE_HSI,

              DISABLE, CLK_CURRENTCLOCKSTATE_ENABLE);

    CLK_PeripheralClockConfig(CLK_PERIPHERAL_SPI, DISABLE);

    CLK_PeripheralClockConfig(CLK_PERIPHERAL_I2C, DISABLE);

    CLK_PeripheralClockConfig(CLK_PERIPHERAL_ADC, DISABLE);

    CLK_PeripheralClockConfig(CLK_PERIPHERAL_AWU, DISABLE);

    CLK_PeripheralClockConfig(CLK_PERIPHERAL_UART1, DISABLE);

    CLK_PeripheralClockConfig(CLK_PERIPHERAL_TIMER1, DISABLE);

    CLK_PeripheralClockConfig(CLK_PERIPHERAL_TIMER2, DISABLE);

}

void delay_us(uint16_t us)

{

  TIM2_DeInit(); 

  TIM2_SelectOnePulseMode(TIM2_OPMODE_SINGLE);

  TIM2_TimeBaseInit(TIM2_PRESCALER_16, us); //Prescalar value 8,Timer clock 2MHz

  TIM2_Cmd(ENABLE);  

  while(!TIM2_GetFlagStatus(TIM2_FLAG_UPDATE));

  TIM2_ClearFlag(TIM2_FLAG_UPDATE);

void delay_ms(uint32_t ms)

{

  while(ms--)

  {

    delay_us(1000);

  }

}

1 ACCEPTED SOLUTION

Accepted Solutions

First, you never call "clock_setup". And second - your "clock setup" function looks scary. If you want to select internal 16MHz oscillator call only one command:

CLK_HSIPrescalerConfig(CLK_PRESCALER_HSIDIV1);

View solution in original post

2 REPLIES 2

First, you never call "clock_setup". And second - your "clock setup" function looks scary. If you want to select internal 16MHz oscillator call only one command:

CLK_HSIPrescalerConfig(CLK_PRESCALER_HSIDIV1);

Thank you @Michal Dudka​ , thanks for pointing out how much of an idiot I am. It is working fine with your inputs