Issue in timer based delay program

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I was working on simple timer based delay (just to understand the concept). I am trying to pulse PD3 every 50 msec. But in the below program, pulsing happens only until counterOne_mS=250.

 

I understand that after 255, counterOne_mS becomes 0.

When counterOne_mS=250, buzzCnt = 250

When counterOne_mS=0, (counterOne_mS-buzzCnt) should be 6 and thereafter counterOne_mS-buzzCnt should get incremented normally I thought. But port pin is not pulsing after 250.

 

I think there is some silly bug in this code. Not able to find it. 

 

volatile uint8_t counterOne_mS;

void initializeTimer0ForOneMilliSec (void)
{

    // In case 16 Mhz crystal is connected, each clock pulse = 1/16 = 0.0625 usec.
    // If we use prescaler of 64, each clock pulse = 0.0625*64 = 4 usec.
    //So we can get 1 msec, we need couner of 1000/4 = 250

    OCR0A = 250-1;          // Set for 1 msec.

    TIMSK0 |= 1<<(OCIE0A);  // Output Compare Interrupt Enable for TimerCounter0 Compare Match A
    TCCR0A |= 1<<(WGM01);  // Mode = CTC: WGM01=1, WGM00=0 in TCCR0A and  WGM02=0 in TCCR0B

    // Timer is activated as soon as the clock source is selected
    TCCR0B = (1<<CS01)|(1<<CS00);   // Timer Prescaler Clock/64, TCCR0B: CS00 - 1, CS01 - 1, CS02 - 0
}

/*one msec counter*/

ISR(TIMER0_COMPA_vect)
{
    counterOne_mS++;
}
int main(void)
{
    DDRD |= 1<<PD3;
    initializeTimer0ForOneMilliSec();
    sei();
    uint8_t buzzCnt=0;
    while(1)
    {
        if((counterOne_mS-buzzCnt)>49)
        {
            buzzCnt=counterOne_mS;
            PORTD|=1<<PD3;
            _delay_ms(3);
            PORTD &= ~(1<<PD3);
        }
    }
    return(0);
}

Compiler: avr8-gnu-toolchain

Last Edited: Sat. May 5, 2018 - 02:27 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

joneewheelock wrote:
When counterOne_mS=0, (counterOne_mS-buzzCnt) should be 6 and thereafter counterOne_mS-buzzCnt should get incremented normally I thought. But port pin is not pulsing after 250.

 

Nope.  The "if" condition is never met.

 

Try just setting a flag in the interrupt.  Do the counting and flag clearing in main.

 

In consideration of others, please RTFM!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I think I got the answer. uint8_t or uint16_t are promoted to int during operation.

It works if I type caste it like

if((uint8_t)(counterOne_mS-buzzCnt)>49)