1

I'm messing about with an Arduino Mega2560r3 and failing to get timer 4 to trigger on the rising edge of an external clock. It only ever triggers on the falling edge.

I've tried

     TCCR4B = (1 << CS42) | (1 << CS41) | (1 << CS40);

and

     TCCR4B = (1 << CS42) | (1 << CS41);

... one of which should do the trick, but now I've pulled all my hair out and I'm turning to the wider community to see what I'm not seeing!

void setup() {
  DDRE = (1 << PE5);   //Dig pin 3 as output

  noInterrupts();
// Configure Timer 4 (only ICP4 (pin 49) and ICP5 (pin 48) are connected with Arduino MEGA2560 r3)
  TCCR4A = 0;
  TCCR4B = 0;
  TCCR4B = (1 << CS42) | (1 << CS41) | (1 << CS40);    // CTC mode does not reset when using force
  TIMSK4 = (1 << ICIE4);    // enable capture interrupt
  interrupts();
}

ISR(TIMER4_CAPT_vect)
{
  PORTE ^= (1 << PE5);  // Toggle PE5
}

Scope output below - blue is external clock (yes I know it's a sine wave!) and magenta is pin 3 output

falling edge trigger output

1

You seem to be mixing up two very different things.

  1. You can use an external signal to drive the timer. That is, the timer will “tick” on the edges of that signal. In this mode, the timer behavior could be more accurately described as being a “counter”, since it is counting the external signal's edges. The external signal has to be fed to pin Tn (for timer n). Only the pins T0 (38) and T5 (47) are routed out on the Arduino Mega2560.

  2. You can use a timer to timestamp the edges of an external signal. This is called “input capture”. When an edge is detected, the current value of the counter register is immediately copied to the input capture register ICRn, and an interrupt can be delivered. The external signal has to be fed to pin ICPn (ICP4 = 49, ICP5 = 48).

If you want to use input capture, you most likely want to clock the timer from the system clock, maybe through a prescaler. And you want to read the ICRn register within the ISR. The edge that triggers the capture is selected via the bit ICESn (Input Capture Edge Select) of the control register TCCRnB.

1
  • Thanks for your help - I mistakenly thought ICPn was also the ext timer input. I'll have to use timer 5 to use get the external clock working, but now you've explained this, I'm not sure which will be more elegant for this aplication... (I tried to upvote your answer but I'm too noob here) Nov 12 '21 at 11:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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