cancel
Showing results for 
Search instead for 
Did you mean: 

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 PD1 pin in each second.

SP.9
Associate II

#include <stdint.h>

#include<iostm8s.h>

void main(void)

{

     

    TIM2_PSCR = 0b00000111; 

TIM2_EGR= 0x01;

TIM1_CR1 = 0x01;

    PD_DDR = 0x01;

PD_CR1 = 0x01;

while(1)

{

if ( ( ((uint16_t)TIM2_CNTRH << 😎 + (uint16_t)TIM2_CNTRL ) >= 15625 ) 

{

TIM2_CNTRH = 0;

TIM2_CNTRL = 0;

    PD_ODR=0X01;

}

else

{

PD_ODR=0X00;

}

 }

}

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?

3 REPLIES 3
Cristian Gyorgy
Senior III

Hi!

It's not bad to be new with MCUs and STM8, it's actually good, and I'm glad to see new people involved in this, so let's see about your code: first, you try to configure TIMER2 but than you enable TIMER1 ("TIM1_CR1 = 0x01;") - this means TIMER2 is not enabled, not running, so can read the counter as long as you want, you'll always read the same value.

Second, even if this is just some startup code, try to do it right. For me it's killing to see an infinite loop reading the counter value. Instead, try to configure your timer right, and use an interrupt to switch the LED.

Good luck!

Cristian Gyorgy
Senior III

Oh, and there is some more: you did not enabled anyway the master clock for any timer. If you want the Fmaster to clock your timer you need to enable it in CLK_PCKENR1 register, if not, even if you set the enable bit in TIMx_CR1 it will not be clocked.

SP.9
Associate II

thank you sir