How do you handle the Timer2 Counter for an External Pin ?
I need to use T2 because I am already using T0 and T1.
I came up with this code, but I do not know the pin, and it just seems to toggle continuously:
void loop()
{
startCnt();
long i ;
for(i=0; i<100000; i++)
{
/// make sure that loop is executed / not optimized out : ///
PORTD |= 0x20 ;
}
GetTimer();
Serial.println( timer2CounterValue );
delay(100);
}
void startCnt()
{
overflow2Count = 0;
// reset Timer 2
TCCR2A = 0;
TCCR2B = 0;
// TIMSK2 = 2; // enable Timer2 Interrupt
TIMSK2 = 1; // interrupt on Timer 1 overflow
// set counter-2 to zero
TCNT2 = 0;
// External clock source on T2 pin (D???). Clock on rising edge.
TCCR2B = 7;
}
ISR (TIMER2_OVF_vect)
{
++ overflow2Count; // count number of Counter1 overflows
}
void GetTimer()
{
/// Get TIMER T2 Counter : ///
word timer2CounterValue = TCNT2; //
unsigned long overflow2Copy = (overflow2Count); //
TCCR2A = 0; // stop timer 2
TCCR2B = 0;
TIMSK2 = 0; // disable Timer2 Interrupt
}
westfw
July 14, 2018, 11:41pm
2
I don't think T2 is able to be clocked from an usable external pin. It can use a clock or crystal connected to the pins that are already dedicated to the crystal...
Thanks for the response !
Actually though, I found an alternate way
(with T0 p4 and T1 p5) - that can give me a Total of 4 pins to Pulse Counters :
INT0 from pin 2
INT1 from pin 3
Example of INT0 from pin2 :
#include <avr/interrupt.h>
long myInt0Cnt = 0 ;
void setup(void)
{
pinMode(2, INPUT);
digitalWrite(2, HIGH); // Enable pullup resistor
sei(); // Enable global interrupts
// Global Enable INT0 interrupt
// GICR |= ( 1 << INT0);
//// GICR |= ( 1 << INT1);
EIMSK |= (1 << INT0); // Enable external interrupt INT0
EICRA |= (1 << ISC01); // Trigger INT0 on falling edge
}
void loop(void)
{
;
}
// Interrupt Service Routine attached to INT0 vector
ISR(EXT_INT0_vect)
{
myInt0Cnt ++ ;
// PORTB ^= (0x20); // Toggle LED on pin 13 TEST // - Fastest way
}
Example of INT1 from pin3 :
#include <avr/interrupt.h>
long myInt1Cnt = 0 ;
void setup(void)
{
pinMode( 3, INPUT);
digitalWrite(3, HIGH); // Enable pullup resistor
// Global Enable INT1 interrupt
// GICR |= ( 1 << INT0);
GICR |= ( 1 << INT1);
// EIMSK |= (1 << INT1); // Enable external interrupt INT1
//falling edge interrupt 1
MCUCR |= ( ( 0 << ISC10) || ( 1 << ISC11) );
}
void loop(void)
{
;
}
ISR(INT1_vect)
{
myInt1Cnt ++ ;
// PORTB ^= (0x20); // Toggle LED on pin 13 TEST // - Fastest way
}