4
\$\begingroup\$

Could somebody please please help me understand the following code. Its running on atmega128 @ 16 Mhz. Its reading an encoder pulse. Uses timer3. The encoder CHA is connected to PIND2 (INT2) which gets triggered whenever there is an interrupt from low to high. CHB of the encoder is connected to PINE7.

I cant quite understand why TCNT3>>3 in this case.

SIGNAL(SIG_INTERRUPT2) 
{ 
   timer3_stop(); 
   Right_Odometer_Period = TCNT3>>3; 
   right_overflow_occurred = timer3_overflowed; 
   timer3_start(); 

   if ((PINE & 0x80) != 0) 
   { 
      right_odometer++; 
      right_up = 1; 

   } 
   else 
   { 
      right_odometer--; 
      right_up = 0; 
      Right_Odometer_Period = Right_Odometer_Period * -1; 
   } 
   Right_Velocity = Right_Odometer_Period; 
   averaging_array[array_ptr++] = Right_Odometer_Period; 
   if (array_ptr == 32) 
   { 
      arraysum = 0; 
      for (int i = 0; i<32; i++) 
      { 
       arraysum += averaging_array[i]; 
      } 
      average = arraysum>>5; 
      array_ptr = 0; 
   } 
} 

void timer3_init(void) 
{ 
   TCCR3A = 0x00; 
   TCNT3 = 0X0000; 
   ETIMSK = (ETIMSK | (1<<TOIE3)); 
   timer3_start(); 
} 

void timer3_start(void) 
{ 
   TCNT3 = 0X0000; 
   timer3_overflowed = 0; 
   TCCR3B = (1<<CS30)|(0<<CS31)|(0<<CS32); 
} 

void timer3_stop(void) 
{ 
   TCCR3B &= ~(1<<CS30)|(1<<CS31)|(1<<CS32); 
} 

SIGNAL(SIG_OVERFLOW3) 
{ 
   TCNT3 = 0X0000; 
        Right_Velocity = 0; 
   timer3_overflowed = 1;    
}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

The best guess I can come up with is that the >>3 (divide by 8) is an attempt to prevent going beyond the size of the variable arraysum. Since TCNT3 is a 16 bit counter, if there wasn't some sort of scaling factor, you could easily end up with a garbage value for arraysum.

That said, the >>3 probably wouldn't completely solve this problem. I think it would depend upon how quickly the encoder is getting spun and the clock speed of the mega128. If each tick on D2 happens to occur when TCNT3 is very large, this algorithm for determining rotational speed is going to have issues.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.