Servo Library on Arduino Mega

Hi everyone,

I'm using one of the 16-bit timers (Timer 4) on the Arduino Mega to orchestrate the sending and receiving of packets on an interrupt every 25ms via a serial port.

The packets contain servo positions, which I wish to apply using the Servo library, and from a quick glance at the Servo code (servo.cpp) I believe that the following line declares the listed timers available for use:

typedef enum { _timer5, _timer1, _timer3, _timer4 } servoTimer_t; // this is the sequence for timer utilization on mega

Would it be acceptable to simply remove the instance of "_timer4" from this list to ensure that the Servo routine does not interfere with my packet handling routine?

Many thanks,

any help with this would be really appreciated. leaving the servo file unmodified, my main program will not compile, giving an error that _vector4 has been defined twice (in the packet transfer ISR within my code, and within the servo file).

Removing "_timer4" as i suggested above causes an error saying something like "_servo4" was not defined.

i have googled all over the place but don't seem to be getting anywhere,

Many thanks,

cant u use multiple interrupt handlers on the same timer? -arne

You don’t need to change anything. The Servo library only allocates timers when they are needed, so as long as you don’t attach more than 36 servos, timer 4 will not be touched.

But if you want to prevent allocating more than 36 servos you can remove _timer4 from the enum.

thanks for the replies, they pointed me in the right direction.

It didn't like having two interrupt vectors assigned to the same timer.

instead of removing the instance from the enum list, i commented out the following lines of code from the servo.cpp file and it compiled and seems to work without any problems:

  handle_interrupts(_timer4, &TCNT4, &OCR4A); 


Good to hear you have it working.

Just to clarify what is happening, removing the enum would prevent the timer from being used by the servo but the servo library is still creating a vector for the compareA interrupt. That’s why you get a link error if you create your own handler for this interrupt.

You can avoiding the link error without changing the cpp file by commenting out the #define _useTimer4 in the Servo.h file.

But the method you also works.