STM8S: Use Timer 2 as Simple Counter to Blink LED (without Interrupt)

Timers inside MCUs are very useful and essential peripherals for timing applications. In this article I will show Timer 2 in an STM8S (specifically STM8S103F3) can be used to blink an LED.

Calculation

STM8S has an internal oscillator with 16MHz frequency. By default it will be used as system clock source with prescaler 8, which means system clock frequency will be 16MHz/8 = 2MHz. By default Timer 2 will run with same frequency as system.

Suppose, we want to toggle LED in each second and we are going to use Timer 2 to identify when 1 second is elapsed.

Each tick of system clock will be 1/2,000,000 = 0.0000005 seconds or 0.5 micro seconds. If we set 128 as prescaler for Timer 2, then timer 2 counter will increment in each 64µs (0.5µs x 128). So, it will be 1 second when timer counter reaches at 15625 (1,000,000/64).

Program

Our LED is connected at PB5 pin (5th pin of port B).

#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
  // Generate an update event so prescaler value will be taken into account.
  TIM2_EGR |= (1 << TIM2_EGR_UG);
  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);
    }
  }
}

I assume the above program code is easily understandable. I will briefly explain it.

  • First, we set PB5 pin as output.
  • Set the prescaler value, 128, for Timer 2
  • Set UG bit of TIM2_EGR register to tell MCU to take prescaler value
  • Enable Timer 2
  • Now within infinite loop, we check if Timer 2 counter value reached 15625 (Timer 2 is having 16 bit counter so we need to combine high and low bytes to get the 16bit value.) If so we know it elapsed 1 second now, then we set counter value to 0 and toggle LED.