thanh cong
thanh cong

Reputation: 11

STM8 Timer1 glitch or stalling issue

Timer error 1 in STM8S003F3P I am writing code to create overflow 1s = Timer 1 to reduce the remaining_sec variable from 60 to 1. But the Timer often hangs for a while at random times. For example, when counting from 60 seconds to 34, it stops there and then continues running after a while. I don't know why? If anyone knows, please help me! Thank you

///////////////////////////////////////
// snippet code file main.c
#include "stm8s.h"

extern volatile uint16_t remain_sec;

void main(){
    _asm("sim\n");
    Clock_config();
    TIM1_config();
    ITC_SetSoftwarePriority(ITC_IRQ_TIM1_OVF, ITC_PRIORITYLEVEL_2);
    _asm("rim\n");

    while (1){
        //notthing to do here
    } 
}

void Clock_config(){
    CLK_DeInit();
    CLK_HSICmd(ENABLE);
    while (CLK_GetFlagStatus(CLK_FLAG_HSIRDY) == RESET);
    CLK_HSIPrescalerConfig(CLK_PRESCALER_HSIDIV1);
}

void TIM1_config(){
    TIM1_DeInit();

    //FCLK/15999 = 1000Hz
    TIM1->PSCRH = 0x3E;
    TIM1->PSCRL = 0x7F;

    //ARR = 999 = 1s overflow
    TIM1->ARRH = 0x03;
    TIM1->ARRL = 0xE7;

    TIM1->IER |= 0x01;  //enable update interrupt
}
///////////////////////////////////////


///////////////////////////////////////
// snippet code file stm8s_it.c

extern volatile uint16_t remain_sec = 0;

INTERRUPT_HANDLER(TIM1_UPD_OVF_TRG_BRK_IRQHandler, 11){
  TIM1->SR1 &= (uint8_t)(~0x01);  //clear UIF

  if(remain_sec > 1){
    --remain_sec;
  }
  //DEBUG
  Serial_print_string("sec=");
  Serial_print_int(remain_sec);
  Serial_print_string("\n");
}
///////////////////////////////////////


I tried running for 5 seconds then it works properly

Upvotes: 1

Views: 14

Answers (1)

Maximilian
Maximilian

Reputation: 175

The code snippet doesn't actually enable the timer, or the peripheral clock to it. It should not work at all as is.

That said... An intermittently working timer could indicate some hardware problems. Try pressing on the IC or flexing the PCB a little. If it stops you have bad solder joints. Hit it with a cold spray... Are the voltage rails stable?

Try toggling an LED in the main loop with a delay. Does that also hang when timer 1 is not counting as expected?

Aside from hardware issues, you could be stuck in an interrupt routine from some code you haven't shown here. Are you sure you have only enabled the one interrupt?

Upvotes: 0

Related Questions