AnsweredAssumed Answered

How to use TIMER 2 as simple counter in STM8S103F3?

Question asked by Junaid PV on Jan 14, 2018

Hi All,

 

I am new to STM8S and not yet that good at microcontroller programming in general. I am trying to learn about timers/counters in microcontrollers.

 

I wrote following code to toggle an LED connected at PB5 pin in each second.

 

#include "stm8s.h"

int main() {
  // Default clock is HSI/8 = 2MHz

  PB_DDR |= (1 << PB5); // PB5 is now output
  PB_CR1 |= (1 << PB5); // PB5 is now pushpull

  TIM2_PSCR = 0b00000111; //  Prescaler = 128
  TIM2_CR1 |= (1 << TIM2_CR1_CEN); // Enable TIM2

  while (1) {
    if ( ( ((uint16_t)TIM2_CNTRH << 8) + (uint16_t)TIM2_CNTRL ) >= 15625 ) {
      // Reset counter back to 0
      TIM2_CNTRH = 0;
      TIM2_CNTRL = 0;

      // Toggle LED.
      PB_ODR ^= (1 << PB5);
    }
  }
}

 

My microcontroller is not connected with any external clock and using internal clock to operate.

 

After I reading datasheet, I see MCU clock will be HSI/8 = 2MHz by default. I set 128 as prescaler for TIM2. So, TIM2 counter will increment in each 64us. So, when it reach at 15625 it will be 1 second (64 * 15625 = 1000000us = 1s).

 

So, I assumed the LED to toggle in each second.

 

The problem is the LED stays ON all time.

 

Could somebody help me to identify the problem with my code?

Thanks in advance.

Outcomes