using timer1 with external clock on T0

I am trying to read a frequency input and then output a different frequency signal according to the input.
For the first part I have been trying to use the timer1 counter to read external clock on pin T0( digital pin 38) on mega 2560 R3. It does not work. If i change clock bit assignment for internal clock, then i will get a count. When i change for external clock and provide a signal using a function generator i get no count reading. Trying to figure out what was done wrong
following is the code used:

int sig = 38; // Pin-T0 

void setup(){
        // start serial communication
        Serial.begin(9600);

        // define pins
        timer1SetExternalClock();
}

void loop(){
        // feedback of counter
        Serial.print("counter ");
        Serial.println(readTCNT1(),DEC);
        //
        delay(300);
}
void timer1SetExternalClock(void)
{
        // Timer1 Setting - Reset - this will also stop the timer
        TCCR1A = 0;
        TCCR1B = 0;
        TCCR1C = 0;
        // clear Timer
        writeTCNT1(0);//
        // normal Mode, immediate update of OCR1A
        TCCR1B |= (0<<WGM13) | (0<<WGM12);
        TCCR1A |= (0<<WGM11) | (0<<WGM10);

        //Timer1 Overflow Interrupt Disable
        TIMSK1 = 0;

        pinMode(sig,INPUT);

        // external clock on pin38 rising edge
         //TCCR1B |= (1<<CS12) | (1<<CS11) | (1<<CS10);
        // this will also start the timer
}

// read and write 16Bit-Counter

void writeTCNT1(unsigned int num) {
        unsigned char sreg;
        unsigned int i;
        if (num >= 0) {
                /* Save global interrupt flag */
                sreg = SREG;

                /* Disable interrupts */
                cli();
                // set new value
                TCNT1 = num;
                /* Restore global interrupt flag */
                SREG = sreg;
        }
}


unsigned int readTCNT1( void )
{
        unsigned char sreg;
        unsigned int i;
        /* Save global interrupt flag */
        sreg = SREG;
        /* Disable interrupts */
        cli();
        /* Read TCNT1 into i */
        i = TCNT1;
        /* Restore global interrupt flag */
        SREG = sreg;
        return i;
}

Are you sure that the external signal is rising and falling far enough to make the clock work?

...R

T0 clocks timer0, T1 clocks timer1. T1 is not, to my knowledge, brought out to an Arduino pin.

1 Like