// COUNT_TRANSITIONS - Arduino
//
// Illustrates how to count positive transistions in input T1.  Digital Pin 5
//
// This uses the Timer1 module which is 16-bits and thus counts up 65535 may be accommodated.
//
// Note that I initially attempted to do this using input T0 (Digital Pin 4).  However, it
// appears that the delay function uses Timer0.
//
// copyright, Peter H Anderson, Baltimore, MD, Nov, '07

#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

#include <avr\io.h>

void setup()
{
    Serial.begin(9600);  
}

void loop()
{
    unsigned int count_transitions(int ms);
    int count;
    
    while(1)
    {
        count = count_transitions(10000);
        Serial.println(count);
    }    
}
             
unsigned int count_transitions(int ms)
{
     // configure Counter 1
     cbi(TCCR1A, WGM11);
     cbi(TCCR1A, WGM10);
     
     cbi(TCCR1B, WGM12);  // WGM12::WGM10 000 - Normal mode
     
     sbi(TCCR1B, CS12);   // CS12::CS10 111 - External clock, count on rising edge.
     sbi(TCCR1B, CS11);
     sbi(TCCR1B, CS10);
    
     TCNT1 = 0x0000;      // note that TCNT1 is 16-bits
     delay(ms);
     // not sure if should turn off the counter
     return(TCNT1);
}